Search code examples
arraysreactjssetstate

How can I setState and push to an array?


this is my state:

class table extends Component {
  state = {
    arr: [],
    numofSub: 1
  };

I wish to push an object to the arr with set state through fetch from my database, the fetch works great I console logged it, I just cant seem to push the object inside the array:

componentWillMount() {
    fetch('/api/items')
      .then(data => data.json())
      .then(inputs => this.setState({ arr: [...inputs] }));

  }

Solution

  • When next state is depended on previous state, is advised to use the functional setstate version:

    componentWillMount() {
        fetch('/api/items')
          .then(data => data.json())
          .then(inputs => this.setState(state => ({ arr: [state.arr,...inputs] })));
      }
    

    As for logging the changes right after setstate you should do that inside the setState's callback. because setState is asynchronous and may not be updated when you log the state:

    this.setState(state => ({key:value}), () => {
      // this is the callback, its safe to log the updated state
      console.log(this.state);
    });