0

I have a state and within that state there is a list with several objects. What I basically want to do is take an index from this array, in this case [0], and change its state. So, in short, I want to take {id: "1", value: "world1"}, and change the id to 'something'. I made a code but it didn't come out as I expected.

this.state = {
   myState: [
              { id: "1", value:"world1" },
              { id: "2", value:"world2" },
              { id: "3", value:"world3" },
            ]
   }

const result = this.setState(prevState => ({
      myState: {
        ...prevState[0].id,
        id: 'something'
      }
    }))

console.log(result)

3 Answers 3

1

Not sure why you need this, but the issue I'm seeing here is that myState is initially an array, and then you're passing it back as an object.

Try this:

const result = this.setState(prevState => {
  prevState.myState[0].id = 'something';
  return prevState;
})
Sign up to request clarification or add additional context in comments.

1 Comment

This will mutate the previous state
1

const state = {
  myState: [{
      id: "1",
      value: "world1"
    },
    {
      id: "2",
      value: "world2"
    },
    {
      id: "3",
      value: "world3"
    },
  ]
}

const setState = (({
  myState
}) => {
  const newState = {
    myState: [...myState]
  }
  const array = newState.myState
  const targetIndex = array.findIndex(({
    id
  }) => id === '1')
  const item = array[targetIndex]
  array[targetIndex] = { ...item,
    id: 'something'
  }
  return newState;
})

console.log(setState(state))

Comments

1

Use Array.prototype.map and object spread operator

this.setState(prevState => {
    return {
        myState: prevState.myState.map(
            myStateItem => {
                if(myStateItem.id === '1') {
                    return {
                        ...myStateItem,
                        id: 'something'
                    }
                }
                return {
                    ...myStateItem
                }
        })
    };
});

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.