1

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?

3
  • Would you provide more code how addFavorite is called, when the state is saved, and where you are logging? Commented Aug 5, 2019 at 16:01
  • 1
    I edit my code, is it ok? Commented Aug 5, 2019 at 16:04
  • You call this.addFavourites(); but returned data from addFavourites() never get stored in any variable ? Commented Aug 5, 2019 at 16:06

1 Answer 1

5

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 });
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah. I get know, forgot to store this to the state. Thank you.
No problem. You should mark the answer if it answered your question.

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.