I think I am probably missing something pretty simple.
in src/api/index.js I have the following:
export async function loginUser(username, password) {
try {
const response = await fetch(`${BASE}/users/login`, {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
user: {
username: username,
password: password
}
})
})
.then(response => response.json())
.then(result => {console.log(result)
const key = result.data.token
localStorage.setItem('stToken', JSON.stringify(key))
localStorage.setItem('username', JSON.stringify(username))
})
return response
} catch (error) {
console.log(error);
}
}
My loginUser is being called in my onSubmit handler in my src/component/login.js
const submitHandler = async (event) => {
event.preventDefault()
setUserData( {username, password})
const response = await loginUser(username, password)
alert({response})
console.log(response.data)
}
This API call returns from the loginUser function, when called by onSubmit:
{success: true, error: null, data: {…}}
data: {token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2M…TU2fQ.4l7g5y8hlEDxlmkWUPiVIfM6XWCqHa0410QXGLy72vw', message: 'Thanks for logging in to our service.'}
error: null
success: true
[[Prototype]]: Object
However, whatever I try to access the return data from the submitHandler (such as console.log or any variation of response.data.token I try, I just get null. As of right now the only way for me to access any API returns in my API folder are via local storage.
Please help me identify what i am missing.
First of all, you are using both promises (.then) and async await.
When you await the fetch.then.then you actually awaits for the last returned value. In your case, since you return nothing (undefined) from your last .then, you can't access the data.
Try return the result -
const response = await fetch(`${BASE}/users/login`, {...})
.then(response => response.json())
.then(result => {console.log(result)
const key = result.data.token
localStorage.setItem('stToken', JSON.stringify(key))
localStorage.setItem('username', JSON.stringify(username))
return result; // this is the line I added
})