Search code examples
reactjsreact-nativeasynchronouslocal-storageasyncstorage

Converting Localstorage to AsyncStorage in React Native


I have a json object that needs to be stored in local storage/async storage.

This is the local storage code and it compiles on the web correctly.

useEffect(()=>{
    const value = localStorage.getItem(`myData${id}`);
    console.log(value);
    if(value){
        setData(JSON.parse(value));
    }
},[])

useEffect(() => {
    localStorage.setItem(`myData${id}`, JSON.stringify(data));
})

And this is how I converted the same code to AsyncStorage for ios (after importing it)

useEffect(()=>{
    const value = AsyncStorage.getItem(`myData${id}`);
    // console.log(value);
    if(value){
        setData(JSON.parse(value));    //ERROR HERE WITH JSON HIGHLIGHTED IN YELLOW 
    }
},[])

useEffect(() => {
    AsyncStorage.setItem(`myData${id}`, JSON.stringify(data));
})

This shows a render error JSON Parse error: Unexpected identifier "object"


Solution

  • You need to wait for AsyncStorage to get your item data:

         useEffect(()=>{
           const fn = async () => {
             const value = await AsyncStorage.getItem(`myData${id}`);
             if(value){
               setData(JSON.parse(value));    
             }
           }
    
           fn();
          },[]);
    

    or

         useEffect(()=>{
           AsyncStorage
             .getItem(`myData${id}`)
             .then( value => { 
               if(value){
                 setData(JSON.parse(value));    
               }
             });
         },[]);