Candace
Candace

Reputation: 53

How do I add to an object that I made in state?

I'm creating an app that logs food submissions and I'm trying to update state for logFood, which is an object, and when I check to see if the state is updated, the state for logFood replaces the previous value. I'd like to add onto the object state and was wondering what options are available? Thank you!

state = {
        food: [],
        displayFoods: false,
        displayLogs: false,
        logFood: {},
        date: "001",
        meal: "breakfast",
        foodsSelected: [],
        reaction: "neutral",
    };


...


 submitFoodLog = () => {

        const date = this.state.date;
        const meal = this.state.meal;
        const foodsSelectedSubmission = this.state.foodsSelected;
        const reaction = this.state.reaction;
        const newLog = {
            dateKey: date,
            mealKey: meal,
            foodSelectedKey: foodsSelectedSubmission,
            reactionKey: reaction,
        };
        this.setState((prevState) => ({
            logFood: { ...prevState.logFood, newLog },
        }));


    };``` 

Upvotes: 2

Views: 57

Answers (2)

Abbasihsn
Abbasihsn

Reputation: 2171

you can use special key for each logged meal. for example:

let t = new Date.now().toString();
this.setState((prevState) => ({
            logFood: { ...prevState.logFood, [t]:newLog },
        }));

Upvotes: 1

Emmanuel Ponnudurai
Emmanuel Ponnudurai

Reputation: 1074

I think you got it right. Except for the fact that your spread operation looks a bit off, I think you need

this.setState((prevState) => ({
  logFood: { ...prevState.logFood, ...newLog }
}));

spread even the newLog basically.

Upvotes: 3

Related Questions