I’m trying to follow the Expo documentation for the Authentication process: https://docs.expo.dev/router/reference/authentication/#example-authentication-context .
I have basically copy-pasted everything in the documentation.
The login flow works as intended, with the context provided as the documentation says — the only change I’ve made is for the Sign-In function. The Sign-in function calls an API, retrieve the JSON and then save the whole data into the session:
return (
<AuthContext.Provider
value={{
signIn: async (username, password) => {
await AuthResp(username, password).then((promise) => {
if (promise) {
const sessionDecode = JSON.parse(promise)
console.log(sessionDecode.usr_type)
switch (sessionDecode.usr_type) {
case "usr":
router.replace({pathname: `/user`})
break;
case "admin":'
router.replace({pathname: `/admin`})
break;
}
}
})
},
signOut: () => {
setSession(null)
},
session,
isLoading,
}}>
{props.children}
</AuthContext.Provider>
);
const AuthResp = async(username, password) => {
console.log(`Trying login for ${username}:${password}...`)
let userSessionJSON = null
try {
const knackPromise = await fetch(`APILINK`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"email": username,
"password": password
})
})
await knackPromise.json().then(async (promise) => {
console.log(promise.session)
if (promise) {
if (promise.errors && promise.errors[0]) {
alert(promise.errors[0].message)
} else {
const userSessionData = {
//sessionData
}
userSessionJSON = JSON.stringify(userSessionData)
await SecureStore.setItemAsync("session", userSessionJSON).then( () => {
setSession(userSessionJSON)
})
}
}
});
setSession(userSessionJSON)
return userSessionJSON
} catch (error) {
alert(error)
console.error(error)
}
}
This works as intended, but I have some issues when the user decides to log-out. When the log-out button is pressed, the session is deleted as intended. However, when the user then decide to log-in again, the session is always “null” the first time and it requires to login again, then it redirect as normal. I’m not sure where I’m going wrong, but I’m quite sure this is some async function I’ve messed up.
What am I doing wrong?
(please ignore the multiple “setSession” i’ve put in the code, it was just for testing)