I am working on a project that uses Laravel for back-end and React for front-end.
Whenever the user clicks login, a modal will open that will, up on submitting, fetch the users bearer token.
These fetch functions are all located inside AuthService.js
export function getLoginToken(email, password) {
fetch("/api/login", {
method: "post",
credentials: 'include',
headers: {
'Accept': 'application/json',
"Content-type": "application/json",
},
body: JSON.stringify({
'email': email,
'password': password
})
}).then((response) => response.json())
.then((responseJSON) => {
return responseJSON;
})
}
The Nav component is where the login button resides, so I'm importing and using the funcionts that I've created inside AuthService.js
When I console log the json result within the actual getLoginToken function, there is no problem. Because up on placing it inside .then()
it waits for it to complete so it doesn't result in undefined.
Now.. Inside the Nav component, there is an onClick
function bound to the login button, which will execute AuthService.getLoginToken(email, password)
Actual problem:
I would like to store the response data inside a variable, but i keep getting undefined. This because I'm trying to insert asynchronous data inside a synchronous function.
I've also tried:
AuthService.getLoginToken(loginEmail, loginPassword).then((result) => {
this.setState({
token: result
});
});
But this will also return: Cannot read property 'then' of undefined.
Any ideas on how to fix this?