1

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"

1 Answer 1

1

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));    
           }
         });
     },[]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.