0

I am not able to solve this setState second night and I'm already desperate. I have heavily nested object which I'm trying to update. In case I have multiple elements in todaysMenu and I'm trying to update state for second element whole array gets "stored" in first element of todaysMenu.

onChangeAnyValue(values, itemIndex) {
        const key = Object.keys(values.x)[0];
        const provideDate = values.date;
        this.setState(prevState => ({
            data: prevState.data.map(day => day.date === provideDate ? {
                ...day,
                todaysMenu: [{
                    ...day.todaysMenu,
                    [itemIndex]: {
                        ...day.todaysMenu[itemIndex],
                        dish: {
                            ...day.todaysMenu[itemIndex].dish,
                            [key]: values.x[key]
                        }
                    }
                }]
            } : day)
        }));
    }

In case I remove square brackets its stored as just objects.

Before

After

Thank you for your time!

1 Answer 1

1

You'll want to change:

todaysMenu: [{
  ...day.todaysMenu,
  [itemIndex]: {
    ...day.todaysMenu[itemIndex],
    dish: {
      ...day.todaysMenu[itemIndex].dish,
      [key]: values.x[key]
    }
  }
}]

...to:

todaysMenu: day.todaysMenu.map((item, index) => 
  index === itemIndex
    ? { ...item, dish: { ...item.dish, [key]: values.x[key] } }
    : item
)

What you currently have is creating an Array with one object instead of converting an Array to a modified Array.

Sign up to request clarification or add additional context in comments.

Comments

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.