I have a react native app. And a logout api call. So I try now to implement the logout api call in react. And the problem I am facing is that the token will not be removed after I called the api call logout. But I tested in swagger and that works. The token have been removed when I trigger the api call logout.
So I have a service:
export const logoutRequest = async () => {
try {
const response = await fetch("http://192.168.1.65:8000/api/user/logout/");
return await response.json();
} catch (error) {
console.log(error);
throw error;
}
};
and a context:
const onLogout = () => {
logoutRequest();
};
and the view that calls the onLogout:
<AuthButton icon="email" mode="contained" onPress={() => onLogout()}>
Logout
</AuthButton>
and to pass the token for the other api data calls. I am using this function"
import AsyncStorage from "@react-native-async-storage/async-storage";
export const retrieveToken = async () => {
try {
const token = await AsyncStorage.getItem("Token");
return token;
} catch (error) {
return null;
}
};
Question: how to remove authentication token in react native?
>Solution :
After the user logout successfully, the app should remove the token
from async storage.
export const removeToken = async () => {
try {
await AsyncStorage.removeItem("Token");
} catch (error) {
console.log("Renove authentication token failed :", error?.message);
}
};
Then
export const logoutRequest = async () => {
try {
const response = await fetch("http://192.168.1.65:8000/api/user/logout/");
await removeToken();
return await response.json();
} catch (error) {
console.log(error);
throw error;
}
};