2

needing some help... how do I update the state to reflect a new schedule being added to a specific child (by id)?

I currently have a form that provides a new set of data that looks like this (with values from the form in the empty strings):

{
  date: '',
  parent: '',
  activity: ''
}

I've created this function below, and I'm passing it the id of the child, and the new schedule which looks like the one above... I'm stuck on this one:

addSched = (id, schedule) => {
  const newSched = this.state.children.map(child => {
    if (child.id !== id) return child;
    return {
      ...child,
      schedules: schedule
    };
  });
  this.setState({ children: newSched });
};

My current state looks like this:

state = {
  children: [
  {
    id: 1,
    firstName: 'Bella',
    lastName: 'Laupama',
    schedules: [
      {
        id: 1,
        date: '25 December 2018',
        parent: 'Chris',
        activity: 'Christmas'
      },
      {
        id: 2,
        date: '31 December 2018',
        parent: 'Laura',
        activity: 'New Years Eve'
      }
    ]
  },
  {
    id: 2,
    firstName: 'Cara',
    lastName: 'Malane',
    schedules: [
      {
        id: 1,
        date: '25 December 2018',
        parent: 'Chris',
        activity: 'Christmas'
      } ...etc

And the component that has the form has the following:

export default class AddSched extends React.Component {
  state = {
   date: '',
   parent: '',
   activity: ''
  }

handleChange = e => {
  this.setState({
   [e.target.name]: e.target.value
  })
 }

submitHandler = e => {
  e.preventDefault()
  this.props.addSched(this.props.id, this.state)
  console.log('SUBMITTED:', this.state)
    this.setState({
    date: '',
    parent: '',
    activity: ''
    })
}
1
  • wouldn't you want to extend the current schedule for the child, rather than to replace it in the addSched function? Commented Nov 20, 2018 at 8:53

1 Answer 1

1

You can use the array spread operator to concatenate the existing array plus the new schedule:

schedules: [...child.schedules, schedule]

Here's the complete function with the change:

ddSched = (id, schedule) => {
  const newSched = this.state.children.map(child => {
    if (child.id !== id) return child;
    return {
      ...child,
      schedules: [...child.schedules, schedule]
    };
  });
  this.setState({ children: newSched });
};
Sign up to request clarification or add additional context in comments.

1 Comment

So like this? addSched = (id, schedule) => { const newSched = this.state.children.map(child => { if (child.id !== id) return child return { ...child, schedules: [...child.schedules, schedule] } }) this.setState({ children: newSched }) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.