Anu
Anu

Reputation: 1742

AsyncStorage.getItem in react native not working

I'm setting data on the server with AsyncStorage.setItem and trying to access that value in another screen using AsyncStorage.getItem. 1. I can't set the token within AsyncStorage. 2. How do I set multiple values within asyncstorage, say I want user_id from server response to be set along with this token?

onPressRegister(){

            fetch('http://192.168.1.7:3000/users/registration',{
                method:'POST',
                headers:{
                    'Accept': 'applictaion/json',
                    'Content-Type': 'application/json',

                },
                body:JSON.stringify({
           contact:this.state.contact,
                     password:this.state.password,
                })
            })
            .then((response) => response.json())
            .then((responseData) =>
            {
                 this.setState({
                     signup: responseData
                 });
                 setTimeout(() => {
                    Actions.firstScreen();
                }, 2300);

        AsyncStorage.setItem('token' ,this.state.signup.token);
            });

    }

And I'm fetching like this

  componentDidMount(){
    AsyncStorage.getItem('token').then((userid) =>{
    this.setState({'userid': userid});
    console.log(userid);
    });
}

But I can't see the result within console nothing is getting. Is there any mistake in AsyncStorage.setItem ?Also, the server response looks like this

{ error: 0,
  data: 'User registered Successfully',
  userData:
   { pwd: 'vgh',
     phone_no: '5',
     user_name: '',
     status: 1,
     date: 2018-10-23T09:23:53.671Z },
  user_id: [  { user_id: 5 } ],
  token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' }

Also I want user_id to be set within AsyncStorage. How to do this?

Upvotes: 0

Views: 5434

Answers (2)

Asif vora
Asif vora

Reputation: 3359

U can use async and await for accessing the value from AsyncStorage.

async componentDidMount(){
    let token = await AsyncStorage.getItem('token');
    console.log(token);
}

Upvotes: 1

Guillaume Piedigrossi
Guillaume Piedigrossi

Reputation: 200

I think your issue come from the async property of setState.

If your responseData is an object (test it with console.log(typeof responseData), Try it :

AsyncStorage.setItem('token' , responseData.token);

Indeed, the setState method take a time to be effective. React native set the state when it is the best moment, and not when you write it in your code (async function). It is not like a variable set..

Another thing to know is when you call getItem. If you call it just after setItem (or even after navigating to another screen), it could not be already set (same async Reason). Then you can do like this to be sure your item has been set :

AsyncStorage.setItem('token' , responseData.token, () => { ...the next instructions (like navigation function) }); 

It is a callback called at the end of the setItem method

Upvotes: 0

Related Questions