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 >
        );
    }
}
Nicolas O
  • 143
  • 2
  • 12
  • After this like updatedAccepted[1] = updatedCount; write this.setState({listings:updatedAccepted}) – iftekhar Apr 03 '19 at 19:08
  • 1
    Possible duplicate of [Correct modification of state arrays in ReactJS](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs) – JJJ Apr 03 '19 at 19:11
  • Thanks a lot @imk for your answer. Would that not update all elements within listings instead of just the accepted array? – Nicolas O Apr 03 '19 at 19:14

1 Answers1

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

Abdelkarim EL AMEL
  • 1,515
  • 1
  • 10
  • 10