Search code examples
reactjsreact-nativeasyncstorage

how to save and get data to local storage in react native?


first I post to get a token, then I save the response in local storage, how do I save and retrieve the token data in local storage using react native?

this is my splashscreen.js

import { api } from '../../helpers'

const getAppToken = () => {
    const post = {
      user: 'dummy',
      secret: 'dummy'
    }

    api.post('/v1/mp/authenticate', post)
      .then(res => {
        const { Data, Message } = res.data
        if (Message === 'SUCCESS') {
          setToken('app-token', Data.token)
          navigation.replace('MainApp')
        }
      })
  }

  const setToken = async (key, value) => {
    try {
      await AsyncStorage.setItem(key, value)
    } catch (error) {
      console.log('error')
    }
  }

  useEffect(() => {
    getAppToken()
  }, [])

and this is api.js from helpers directory

import { axios, AsyncStorage } from '../../libraries'

export const api = axios.create({
  baseURL: 'dummy',
  headers: {
    'X-APP-TOKEN': 'dummy',
    'X-Requested-With': 'XMLHttpRequest',
    'content-type': 'application/merge -patch+json'
  }
})

AsyncStorage.getItem('app-token')
  .then(token => {
    api.interceptors.request.use(config => {
      config.headers = { Authorization: `Bearer${token}` }
      return config
    }, error => {
      console.log(error)
      return Promise.reject(error)
    })
})

when the AsyncStorage.getItem ('app-token') located in the api.js file is run it gets a 401 response


Solution

  • initialPage screen

     axios.post('https://your_apikey', {}, {
            headers: { 'Authorization': `Basic c2hvcHBpbmdfb2F1dGhfY2xpZW50OnNob3BwaW5nX29hdXRoX3NlY3JldA==` }
        }).then(async (response) => {
            console.log(response.data.data.access_token);
            await AsyncStorage.setItem("token", response.data.data.access_token);
        }).catch((error) => {
            console.log(error);
        });
    

    Homepage//my project as ur wish were u want(second initial page )

    axios.interceptors.request.use(
            async config => {
                const token = await AsyncStorage.getItem("token")
                if (token) {
                    // console.log('if condition', await AsyncStorage.getItem("token"));
                    config.headers.Authorization = "Bearer " + token//pass ur token entire app once ur set
                } else {
                    console.log('config');
                }
                return config
            },
            error => {
                return Promise.reject(error)
            }
        );