3

When I run my code like this, the console shows an empty array. However when I use console.log(res.data) I get the expected json object of employees without a problem.

  state = {
    userList: [],
    firstName: "",
    lastName: "",
    position: ""
  };

loadUsers = () => {
  API.getUsers()
    .then(res =>
      this.setState({ userList: res.data, firstName: "", lastName: "", 
      position: "" })
    )
    .then (console.log(this.state.userList))
    .catch(err => console.log(err));
};

Either way the code is run I also get an Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () error message.

  • is res.data a string or an object - do console.log(typeof res.data) – jsdeveloper Mar 19 '19 at 21:21
  • 2
    `.then (console.log(this.state.userList))` should be `.then (() => console.log(this.state.userList))`. However, note that `setState` doesn't update the state immediately. https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous – Felix Kling Mar 19 '19 at 21:32

2 Answers2

5
     .then (console.log(this.state.userList))

That immeadiately calls console.log, logs the current state (way before the async stuff even starts), console.log returns undefined and the whole thing evaluates to

 .then(undefined)

Instead, pass a function to .then, e.g.

.then(() => {
  console.log(this.state);
});

However as setState is also asynchronous, that won't work reliably. Therefore you should use the callback that one can pass to setState, so that you log after the async action was done and the state was updated:

this.setState(
  { userList: res.data, firstName: "", lastName: "", position: "" },
  () => console.log("done", this.state)
)
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

setState is asychronous so you are not guaranteed to have the state value updated by the time you are checking it with console.log

async/await to the rescue

state = {
  userList: [],
  firstName: "",
  lastName: "",
  position: ""
};

loadUsers = async () => {
  const response = await API.getUsers();
  this.setState({
    ...state,
    userList: response.data, 
  }, () => console.log('[user list]', this.state.userList)
};

Update

Added the spread syntax

Mark
  • 1,610
  • 1
  • 14
  • 27
  • 3
    [`...` is not an operator!](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508) – Felix Kling Mar 19 '19 at 21:33