Stan
Stan

Reputation: 130

React - Adding a property to an object inside of array in component's state

I am fetching an array of objects in the state, and I am trying to add a property to each of these objects.
The problem is I can see my property being added to each of the objects but when I mapping through all these objects and trying to console.log it I'm getting undefined

Adding a property

addFavourites() {
        let data = this.state.data.map((e) => {
            e.favourite = false;
            return e;
        });
        return data;
    }
state = {
        data: []
    }

addFavourites's called here:

getItem = () => {
        this.service
            .mergeData()
            .then((body) => {
                this.setState({
                    data: body
                },
                () => {
                    this.addFavourites();
                },
                () => {
                    this.dataToFilter();
                });
            });
    }

    componentDidMount(){
        this.getItem();
    }

In render function I see all my objects including favourite

console.log(data.map((e) => e));

But this gives an array of undefined

console.log(data.map((e) => e.favourite));

How can I solve this?

Upvotes: 1

Views: 6429

Answers (1)

Gershon Papi
Gershon Papi

Reputation: 5106

First, welcome! You should have probably made it more clear that this question is about React.

Now to the answer, every state modification would be made using setState, so your addFavourites function should be like this:

addFavourites() {
    let data = this.state.data.map((e) => {
        e.favourite = false;
        return e;
    });
    this.setState({ data: data });
}

Upvotes: 5

Related Questions