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
-
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 ☺️