0

this is my first stack overflow post so I hope I explain this well enough. I am having trouble with a fetch request to my api. It is returning the correct data. However, I believe the issue is with the promise being returned is asynchronous as well as the function calling the fetch. handleSubmitLogin is a call back function from my Login component.

handleSubmitLogin = (loginInformation) => {
    var userInfo = this.getUser(loginInformation);
    this.setState({loggedIn:true, currentUser:userInfo})
}    

getUser(loginInformation) {
fetch('http://localhost:3001/api/getUser', {
  body: JSON.stringify(loginInformation),
  cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
  credentials: 'same-origin', // include, *omit
  headers: {
    'content-type': 'application/json'
  },
  method: 'POST', // *GET, PUT, DELETE, etc.
  mode: 'no cors', // no-cors, *same-origin
})
.then( (res) => {
  var userInfo = res.json();
  console.log(userInfo)
  return userInfo
})

}

Essentially, I know it is trying to setState withough having the userInfo because the promise is pending. I tried running the setState inside the .then instead but this caused React to refresh the page for some reason.

Any help would be appreciated, and if you need to see more code let me know! Thanks!

0 Answers0