Search code examples
react-nativeasyncstorage

How to fix Error : variable is read-only in react-native?


How to fix Error : variable is read-only in react-native ?

When i trying to used key of Asyncstorage in another screen.Then it give me this below error.

Please help me how i can solved it.Thank you in advanced.

enter image description here

This code is for store value of my API response in Asyncstorage.

let iGuserData = response.ResponseCode;
                    AsyncStorage.setItem('updateddata',JSON.stringify(iGuserData) )
                    console.log("async updated data",iGuserData);

This is my constantData.js file code.where i trying to add key of Asyncstorage.

export const identfyGenderData= 'updateddata'

This is some part of code of my welcomescreen.js file code.Where i trying to access value of Asyncstorage.

import {identfyGenderData} from '../Component/constantData';
const profilefirst= AsyncStorage.getItem(identfyGenderData)

componentDidMount(){this.userExist()}
  userExist=()=>{

    if (profilefirst=1) {
      this.props.navigation.navigate('InterestedinScreen')
    }else{
      this.props.navigation.navigate('IdentifygenderScreen')
    } 
  }

Solution

  • AsyncStorage is an async function, So wait until AsyncStorage fetch identfyGenderDatainside using Async/await.

    userExist = async () => {
      try {
        const profilefirst = await AsyncStorage.getItem(identfyGenderData);
        if (profilefirst == 1) {
          this.props.navigation.navigate("InterestedinScreen");
        } else {
          this.props.navigation.navigate("IdentifygenderScreen");
        }
      } catch (error) {
        // Error retrieving data
      }
    };
    

    Hope this helps you. Feel free for doubts.