Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove authentication token with react native?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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;
  }
};


Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading