Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

null is not an object (using async storage)

I’m trying to implement secure store (like async storage) into my testproject and it works. The only thing that doesn’t work appears to be my load() useEffect that runs every time I start a new session.

  • So every time I start the session "null is not an object" appears and throws errors at every part where I’m looking for my list on my home-screen (my state is called goals).

  • but if I temporarily turn it off, add a goal to my list, and then turn it on – it works fine every time I restart the app

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  • I feel like I need to write a condition in my load() statement but I can’t figure out what, I think the app runs the load() and gets stuck at the statements where I use goals before I’ve added any. Can someone help me here? I’ve tried if (goals !== null) but it doesn’t work.

     const [goals, setGoals] = useState([])
    
          const load = async() => {
          if (goals !== null) {
          try {
              const goalsValue = await SecureStore.getItemAsync('Goals'); 
              setGoals(JSON.parse(goalsValue))
          }catch (err) {alert(err)}
        }}
    
        useEffect(()=> {
           load()
        },[])
    

>Solution :

So what is happening is that there’s nothing inside goalsValue so when you try parsing it you get an error. To avoid that you should add an if statement that checks if it’s empty or not

const [goals, setGoals] = useState([])

      const load = async() => {
      if (goals !== null) {
      try {
          const goalsValue = await SecureStore.getItemAsync('Goals'); 
          if(goalsValue) setGoals(JSON.parse(goalsValue))
      }catch (err) {alert(err)}
    }}

    useEffect(()=> {
       load()
    },[])

Try this and let me know if it works ☺️

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading