Issue
I have a very simple Fetch API call as part of a React Native project. I'm seemingly able to receive the response data (verified with Console.log()
), but for some reason, my data isn't being transferred into useState()
properly. I haven't had any difficulties doing this before.
This is where I'm trying to store my data:
const [data, setData] = useState("");
And this is my API call:
fetch('https://api.panodime.com/v1/oauth-login?email=' + email + '&token=' + token, {
headers: { 'X-ApiKey': 'doxy08E9SqxTvgvFpB3yOEGCO4YE77m88iSXTQ5TZrcpf3Qw' }
})
.then((response) => { return response.json() })
.then((response) => { console.log(response.data.authToken)})
.then((response) => setData(response.data.authToken))
//.then(() => console.log(data))
//.then(() => storeData(data))
//.catch((error) => console.error(error))
The test data I'm using for the input parameters to the fetch API call are email: [email protected]
and token: 235906121209210
.
The strangest thing is that the line .then((response) => { console.log(response.data.authToken)})
returns the authToken that I want successfully, but when I call it in .then((response) => setData(response.data.authToken))
, it says that it's undefined. Any help would be appreciated.
Solution
This is a short lesson for Promise and Thenables.
If you want to have multiple thenables like this, you need to ensure you return the value, so it can be pass on to the next function.
e.g.
.then((response) => {
console.log(response.data.authToken)
return response //this pass response to next function
})
.then((response) => setData(response.data.authToken))
Answered By - Someone Special
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.