0

I was wondering about how to replace the item if it already exists inside state array and I got a great solution

https://codesandbox.io/s/4xl24j7r69

It works fine but my problem is I can't add a new item if the item doesn't exist inside the array I got an error Cannot convert undefined or null to object

Like this:

add = () => {
    let newUser1 = {
      "userId": 1,
      "id": 3, // this is new id which is doesn't exist in this.state.data
      "title": "Two New",
      "body": "new data"
    }

    this.setState(prevState => {
      let newData = prevState.data;
      let user = newData.find(d => d.id === newUser1.id);
      Object.assign(user, newUser1);
      return { data: newData };
    })
  };
2
  • 1
    Try changing Object.assign(user, newUser1); to Object.assign({}, user, newUser1); Commented Mar 15, 2018 at 23:36
  • @SrThompson its not working codesandbox.io/s/4xl24j7r69 Commented Mar 15, 2018 at 23:44

1 Answer 1

1

You're not adding the newUser to the data on state.

add = () => {
    let newUser1 = {
      "userId": 1,
      "id": 4,
      "title": "Two New",
      "body": "new data"
    }

    this.setState(prevState => {
      const user = prevState.data.find(d => d.id === newUser1.id);
      if (!!user) {
        //Casting user to a boolean, if find did return a truthy value you add it to the data with map
        Object.assign(user, newUser);
        const newData = prevState.data.map(d => d.id === user.id ? user : d);
        return { data: newData }
      } else {
        return { data: prevState.data.concat(newUser1)};
      }
    })
  };
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, now I can add item but if the item already exist I can't update it as before
Yeah, my bad, you did need Object.assign :D I was just fixing it. Anyway, you should always use that method as Object.assign({}, ...etc) because JAVASCRIPT

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.