Home > Software design >  how to store a auth token in react native from api responce
how to store a auth token in react native from api responce

Time:01-03

i am trying to store the response.data.token into sessionstorage or localstorage how can i do it from inside the axios then

   const getdata = async () => {
    var date2 = moment(mydate2).format('DD/MM/YYYY');
    var date = moment(mydate).format('DD/MM/YYYY');
    var todaydate = moment(new Date()).format('DD/MM/YYYY');
    if (date == todaydate && date2 != todaydate) {
      var Data56 = {
        name: name,
        email: email,
        babyname: babyname,
        phone: nuber,
        period: date2,
        // baby_date: date,
      };
    } else {
      var Data56 = {
        name: name,
        email: email,
        babyname: babyname,
        phone: nuber,
        // period: date2,
        baby_date: date,
      };
    }

    axios({
      method: 'POST',
      url: 'http://127.0.0.1:8000/api/register',
      data: Data56,
    })
      .then(async response => {
        await AsyncStorage.setItem('token', `${response.data.token}`);
        alert('sucess ');
      })
      .catch(error => {
        alert(JSON.stringify(error.response.data));
      });
  };

enter image description here

i am trying to store the response.data.token into sessionstorage or localstorage how can i do it from inside the axios then

CodePudding user response:

==> Update Your code like this:-

    .then(function async(response) {
    try{
        await AsyncStorage.setItem('token', response.data.token);
    }catch{
       console.log("Catch Function")
    }
         

CodePudding user response:

Setting data to Asyncstorage works asynchronous so you need set with await like this:

axios({
      method: 'POST',
      url: 'http://127.0.0.1:8000/api/register',
      data: Data,
 
    })
   .then(async (response) => {
         
       await AsyncStorage.setItem('token', `${response.data.token}`);
         alert("sucess ");
   
      })
      .catch(error => {
        alert(JSON.stringify(error.response.data));
      });
  }
  • Related