1

I am trying to setState after an API call, and I know this is an async task but I can't figure out how to update my state. My code looks like this:

loadUserDetails = () => {
    this.setState({
        isLoading: true,
        status: "Fetching user details..."
    }, () => {
        fetch('url', { method: 'Get', credentials: 'include' })
            .then(res => res.json())
            .then((data) => {
                console.log("results")
                console.log(data.name);
                console.log(data.surname);
                console.log(data.emailAddress);
                this.setState({
                    userProfile: data
                })
                if (this.state.userProfile != null)
                    this.loadRolesData();
                })
            })
        });
        .catch(console.log);
}

The console logs are producing the correct values but when I try to update the userProfile to data it doesn't happen. Reading the docs I can see useEffect as a solution but unsure how to implement it.

Edit:

I am initiating this from componentDidMount(). I think this is the correct place but happy to be told otherwise.

2 Answers 2

0

I think you did the task in the wrong order.

Do fetch for the api, afterwards do setState. Here's one simple example.

  fetch(...).then(res => {
    this.setState({...})
  })

Please don't get confused about the second parameter of setState, that is to wait till state to finish update. Normally that is designed for some special occasion, 99% of time you don't need that.

3
  • He did it in the correct order. First setState is for setting the isLoading flag to true. There is a second one in the then() callback for the actual data.
    – comonadd
    Feb 10, 2021 at 21:52
  • Don't you think that is a bit crazy, why not start with a flag without calling setState? const [a] = useState(false)
    – windmaomao
    Feb 10, 2021 at 21:56
  • He obviously doesn't know how to use React Hooks. Yes, I agree, even without react hooks, there is no real need to call fetch() only after setting the loading flag because it doesn't depend on it, but that was in his original code and you misunderstood it.
    – comonadd
    Feb 10, 2021 at 22:04
0

setState doesn't update the state immediately after the call, and so that's why there is a second argument (callback). It is fired only when the update is finished. You used that second argument in your first setState call actually. So you can either do the same thing in the second call:

this.setState({
  isLoading: true,
  status: "Fetching user details..."
}, () => {
  fetch('url', { method: 'Get', credentials: 'include' })
    .then(res => res.json())
    .then((data) => {
      console.log("results")
      console.log(data.name);
      console.log(data.surname);
      console.log(data.emailAddress);
      this.setState({
        userProfile: data
      }, () => {
        // this code will get fired only after the state updates
        if (this.state.userProfile != null) {
          this.loadRolesData();
        }
      })
    })
    .catch(console.log);
});

Or you can use react hooks which would require you to refactor your component into a function and rewrite your fetch logic like the following:

const [userProfile, setUserProfile] = React.useState(null);
const [isLoading, setIsLoading] = React.useState(false);

// This function will get fired every time the userProfile state updates
React.useEffect(() => {
  if (userProfile != null) {
    loadRolesData();
  }
}, [userProfile]);

const loadUserProfile = () => {
  setIsLoading(true);
  setStatus("Fetching user details...");
  fetch('url', { method: 'Get', credentials: 'include' })
    .then(res => res.json())
    .then((data) => {
      console.log("results")
      console.log(data.name);
      console.log(data.surname);
      console.log(data.emailAddress);
      setUserProfile(data);
      setIsLoading(false);
    })
    .catch(console.log);
};
1
  • Your first solution didn't work for me sadly. The state is still not updated
    – UBS_Steve
    Feb 10, 2021 at 22:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.