3

I have an array of objects (language codes and names) that I am trying to spread into another array in local state in a react component. The structure of the array I am trying to spread is like this:

let langs = [
  {code: "af", name: "Afrikaans"},
  {code: "sq", name: "Albanian"}
]

I am trying something simply like this:

this.setState({
  languages: [...langs]
}, 
  console.log(this.state.languages);
);

When I try to console.log languages in the callback from setState the array is empty. What am doing wrong here?

1
  • 1
    setState is an async action. Use the console.log() in the setState callback, or in render(); Commented Apr 24, 2018 at 7:18

2 Answers 2

3

setState is async, and you need to invoke the function in the callback.

this.setState({
  languages: [...langs]
}, () => console.log(this.state.languages)
);
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhhhh I feel so stupid now, thanks Stanley and Jamiec!
2

The second parameter is a callback - you're executing console.log immediately and passing its result as the callback. Change you code to this:

this.setState({
    languages: [...langs]
  }, 
  () => console.log(this.state.languages);
);

Comments

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.