0

I am trying to change a value of an array that is in an another array using React.

Here is my array:

routes = [
    {
        id: 1,
        points: [{id, address, status}, {id, address, status},]
    },
    {
        id: 2,
        points: [{id, address, status}, {id, address, status},]
    },
]

And how I have set it up. When user clicks on "Accept" then the status of that specific point should change.

{routes.map((route, i) => (
    <div>...</div>
    {route.points.map((point, i) => (
        <Button onClick={() => this.onAcceptClicked(route.points)>Accept</Button>
    ))}
))}

Here I am trying to change the value but I am missing something or doing everything completely wrong. Status of that specific point should be set to 2.

onAcceptClicked = (points) => {
    const myNewArray = Object.assign([...points], {
        [index]: {
            ...deliveryPoints[index],
            status: 2
        }
    });
    //this.setState({ points: myNewArray }); ... not sure how to do this part
}

1 Answer 1

1

You will have to update the whole routes in the state.

As you already have the index you can skip the finding part

{routes.map((route, i) => (
    <div>...</div>
    {route.points.map((point, j) => (
        <Button onClick={() => this.onAcceptClicked(route.points,i,j)>Accept</Button>
    ))}

And update the routes in state like below (i is the index of the item in routes array and j is the index of item in points array)

onAcceptClicked = (points,i,j) => {
    const myNewArray = [...this.state.routes];
    myNewArray[i].points[j]={...myNewArray[i].points[j],status:2};
    this.setState({ routes: myNewArray }); 
}

))}
Sign up to request clarification or add additional context in comments.

14 Comments

No I mean you need to create the whole structure again down to the level where the update has to be made, not only the top level. This needs to be done to ensure that if a nested element is passed down as a prop it will be recognised as changed. In your answer you replace the top level array with a new array which is correct but in that array you are still mutating the object instead of replacing it.
It might not be a problem in most apps as if a parent re-renders it will re-render its children. But if a child makes a shallow comparison of its props and one prop is the nested object it might break.
and the value of the newArray before setting state ?
I simply dont get it.. I have it exactly the same way and its changing both.. I will let you know once I figure it out, thank you for everything.
|

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.