Reputation: 1
I am working on an application in which after logging in we are redirected to the protected route but I am facing an issue, when I enter username and password and hit login it is successfully calling the API and setting the token in localstorage
but it is not redirecting to the protected route but when I enter credentials again then it is working fine.
Here is the code where I guess is having problem:
const submitAction = (data) => {
dispatch(login(data));
history.push(`${private_component}`);
};
data is basically username and password and I am using Redux that's why dispatching the login action where I am calling API and storing tokens in localstorage
and user-related data in redux.
I guess the history.push
is being called before the tokens get stored in localstorage
. Can anyone suggest me solution?
Upvotes: 0
Views: 49
Reputation: 603
You may want the login
action to return a Promise, so you can wait until the API call is finished. What's probably happening is that you're pushing to the protected route before the line above has finished, so the user isn't actually logged in. That would also explain why it works the second time around. Another possibility would be to move the redirect into the login action itself, as long as it's handled after the response is received and the user is logged in.
export function login = (username, password) => (
new Promise((resolve, reject) => {
// your code
fetch('wherever', {whatever: 'config'} ).then(r => r.json()).then(d => resolve(d)).catch(e => reject(e))
}
)
something like that may allow you to then do
const submitAction = (data) => {
dispatch(login(data))
.then(history.push(`${private_component}`));
}
this is really just psuedocode, so forgive any mistakes that may not work exactly, but hopefully it gets the idea across.
Upvotes: 1