How to store values in session using React Native?

4.5k views Asked by At

I've set the location as session variable at user registration (index.js) using AsyncStorage.setItem. I am trying to access this session variable in Profile.js. But when i tried to print the session variable (location) nothing is getting.Following is my code.What wrong i'm doing? please help

index.js

AsyncStorage.setItem('location').then((location) =>{
            this.setState({ location: location })
        })

Profile.js

fetch('http://loaclhost/apps/requirement.php',{
        method:'POST',
        headers: {
            'Accept':'application/json' ,
        },
        body: JSON.stringify({
            location:this.state.location,   
        })
    }).then( () =>
    {

        response => response.json();
    AsyncStorage.getItem('location').then((location) => {
        this.setState({location: location})
    })

    render(){
            return(
            <Container>
             <View>
            <TextInput 
        value={this.state.loctaion} />
             </View>
            </Container>
        );
    }
1

There are 1 answers

9
Pratik S. Gode On BEST ANSWER

This may help you,

index.js

AsyncStorage.setItem('location_key', 'location_value').then((location) =>{
    this.setState({ location: location })
})

Profile.js

var getLocation = function(){
    return AsyncStorage.getItem('location_key')
}

var fetchCall = function(location){
    return fetch('http://loaclhost/apps/requirement.php',{
        method:'POST',
        headers: {
            'Accept':'application/json' ,
        },
        body: JSON.stringify({
            location: location, //Resolved location
        })
    })
}


function fetchRequest(){

    getLocation()
    .then(fetchCall)
    .then((response) => {
        //Response handling
    })
}