I have a react native app. And I have a logout function. The problem I am facing is that sometimes the logout function doesn’t work.
For example when I start the app and then I choose for logout the screen doesn’t react. In other words it doesn’t go back to the login screen.
And I looked for the token. But the token is at that moment not set.
So I have a authcontext:
import {
AccountRequest,
AccountUpdateRequest,
loginRequest,
logoutRequest,
} from "./authentication.service";
import { createContext, useEffect, useState } from "react";
import { useNavigation } from "@react-navigation/native";
import AsyncStorageLib from "@react-native-async-storage/async-storage";
import { useToast } from "react-native-toast-notifications";
export const AuthContext = createContext();
export const AuthContextProvider = ({ children, navigation }) => {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [token, setToken] = useState(null);
const [user, setUser] = useState(null);
const toast = useToast();
useEffect(() => {
if (token === null) {
navigation.navigate("Login");
}
AsyncStorageLib.getItem("Token").then((t) => setToken(t));
});
const onLogin = (email, password) => {
setIsLoading(true);
loginRequest(email, password)
.then((u) => {
setUser(u);
setToken(u.token);
setIsLoading(false);
})
.catch((e) => {
setIsLoading(false);
toast.show("Email of wachtwoord incorrect. Probeer het nog eens", { type: "warning" });
});
};
const onLogout = () => {
logoutRequest().then(() => {
setUser(null);
setError(null);
});
};
return (
<AuthContext.Provider
value={{
isAuthenticated: !!user || !!token,
isLoading,
error,
user,
onLogout,
}}>
{children}
</AuthContext.Provider>
);
};
and the api call:
export const logoutRequest = async () => {
const token = await retrieveToken();
try {
if (token) {
const response = await fetch(`${API_URL}/api/user/logout/`, {
method: "POST",
headers: {
Authorization: `token ${token}`, // Something like this, depending on your implementation
},
});
removeToken();
return await response.json();
} else {
throw new Error(token);
}
} catch (error) {
Error("can't retrieve data");
}
};
Question: how to force to go to loginscreen when there is no token set?