0

I would like to have a code which updates the first entry in my array with a button click.

Does anyone have an idea what the solution could be?

Many thanks in advance,

Nicolas

I already tried the code attached.

class JobBuilder extends Component {
    state = {
        listings: {
            accepted:  [0,0,0,0,0,0,0,0,0,0]
        }
    }
    acceptedHandler = () => {
                    const updatedCount = 1;
                    const updatedAccepted = {
                    ...this.state.listings.accepted        
                    }
                    updatedAccepted[1] = updatedCount;
                } 

    render () {
        return (
            <Aux>
                <JobList 
                    listings={this.state.listings}
                    <button onClick={this.acceptedHandler}>Accept</button> 
            </Aux >
        );
    }
}
3
  • After this like updatedAccepted[1] = updatedCount; write this.setState({listings:updatedAccepted}) Commented Apr 3, 2019 at 19:08
  • 1
    Possible duplicate of Correct modification of state arrays in ReactJS Commented Apr 3, 2019 at 19:11
  • Thanks a lot @imk for your answer. Would that not update all elements within listings instead of just the accepted array? Commented Apr 3, 2019 at 19:14

1 Answer 1

1

The spread operator for arrays is []

updatedAccepted[1] will update the second entry instead of the first one.

Have a look at below code :

 acceptedHandler = () => {
    const updatedCount = 1;
    const clonedListing = {...this.state.listings};
    const updatedAccepted = [...clonedListing.accepted]
    updatedAccepted[0] = updatedCount;

    this.setState({
      listings: {
        ...clonedListing,
        accepted: updatedAccepted
      }
    });
} 

Working stackblitz

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

4 Comments

Thanks so much - this is the solution. Really appreciate your help!
Is it possible that this code deletes all other states in listings as well? It correctly updates my listings -> accepted, but seems to delete the other states in listings too.
i've updated the code and the stackblitz for this case, can you check ?
Thanks alot again!

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.