skip to Main Content

i am new to react native i am trying to store the generated token from API to a storage so I can access it from anywhere in my application the generated token Is available in response.data.token i want to store it in something like session storage or local storage to access it from

  axios({
      method: 'POST',
      url: 'http://127.0.0.1:8000/api/register',
      data: Data,
     
    })

      .then(response => {
      alert(JSON.stringify(response.data.token));

      })
     
      .catch(error => {
       alert(JSON.stringify(error.response.data));
      });
  }

also pls let me know how i can check for if the token is stored in React Native debugger

3

Answers


  1. You can use Redux to Store the Session Token
    and with useSelector you can access token all over the app .

    You can go through with these documentations
    Link 1
    Link 2

    Login or Signup to reply.
  2. If you just want to save some data in an unsecured way and access it from anywhere, then yes, Async Storage is your option.

    Just install the Async Storage like that:

    yarn add @react-native-async-storage/async-storage
    

    And then in any async function, you can call this to set data:

    await AsyncStorage.setItem('your_data_identifier', data);
    

    And call this to get data:

    const data = await AsyncStorage.getItem('your_data_identifier');
    

    More here https://react-native-async-storage.github.io/async-storage/

    If you want a more secure way, there are a few libs, like this for example:
    https://github.com/talut/rn-secure-storage

    Login or Signup to reply.
  3. You have to use @react-native-async-storage/async-storage library to store the token in LocalStorage.

    After that use it like this.

    import AsyncStorage from '@react-native-async-storage/async-storage';
    
    axios({
      method: 'POST',
      url: 'http://127.0.0.1:8000/api/register',
      data: Data,
     
    })
    
      .then(response => {
      alert(JSON.stringify(response.data.token));
      AsyncStorage.setItem('token', JSON.stringify(response.data.token));
      })
     
      .catch(error => {
       alert(JSON.stringify(error.response.data));
      });
    }
    

    Actually there is no exact way to check that token is available in the LocalStorage or not but you can console.log() it and check.

    For checking it.

      useEffect(() => {
        const getUserToken = async () => {
         const token = await AsyncStorage.getItem('token'); 
           console.log("token",token)   
        };
        getUserToken();
      }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search