1

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] }));

  }
2
  • 1
    this.setState({ arr: [...this.state.arr, ...inputs] }) Commented Sep 22, 2018 at 18:05
  • thank you for your reply, I tried that and I get an empty array when I console log the state, like so: [] ​ length: 0 ​ <prototype>: Array [] Commented Sep 22, 2018 at 18:08

1 Answer 1

2

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

wonderful it works, I completely forgot it was asynchronous, thank you!
@AlexAlex Glad i could help

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.