Issue
This is part of my code. The login function I use in an onClick button:
const {user, setUser} = useContext(UserContext)
const login = () => {
const errors = validateForm(fields);
setErrors(errors);
if (!errors.length) {
const username = fields.find((field) => field.id === 'username').input.state.value;
const password = fields.find((field) => field.id == 'password').input.state.value;
setUser(username);
APIService.LoginUser({username, password})
}
}
It basically checks in the validateForm(fields) whether the user put something in the form. If there are no errors there, then it sets the user variable to be whatever the user inputted as the username. And that user I hope to be made available to other pages so the app knows who is logged in.
This is the APIService.LoginUser() code:
export default class APIService {
static LoginUser(username, password) {
return fetch(`http://localhost:5000/userlookup`, {
'method':'POST',
mode: 'cors',
headers: {
'Content-Type':'application/json'
},
body: JSON.stringify(username, password)
})
.then(resp => window.location.href = "profile")
.catch(error => console.log('error time!', username, password))
}
The idea is that once the user is logged in successfully, the site will go straight to the "profile" page. On the profile page I have a simple greeting:
const Profile = () => {
const {user, setUser} = useContext(UserContext);
return (
<IonPage>
<IonContent>
<h1>
Hi, {user}
</h1>
</IonContent>
</IonPage>
)
};
export default Profile;
(from the tags, you can see that this is an ionic app, but I believe that is irrelevant)
My problem is that when I try to log in using the above code, after I get redirected to the profile page the greeting does not update with the username of the user that is logged in. However when I comment out this section of the LoginUser function:
.then(resp => window.location.href = "profile")
.catch(error => console.log('error time!', username, password))
and manually navigate to the profile page, it works correctly! It greets the logged in user! Is this an async problem? My theory is that when it automatically redirects to the profile page it does it too fast for the UseContext to tell it what to do? Is this theory true? Is it something else? How do I troubleshoot this?
Thanks
Solution
window.location.href = "profile"
that is not the correct way to navigate to different pages in Ionic Framework
const history = useHistory()
and then to go to another route
history.push("/profile")
See documentation - https://ionicframework.com/docs/react/navigation#ionreactrouter
Answered By - Aaron Saunders
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.