React Native setState issues using true false and null

Viewed 330

I am trying to setState on something that may be true false or null. I am having issues and looking for a clean way to code

does not work

setFullCalendar(await AsyncStorage.getItem('@calendar') === 'true' || null ? true: false);

Works but I can not set if null

setFullCalendar(await AsyncStorage.getItem('@calendar') === 'true' ? true: false);

Works but not clean. (not clean because I have over 10 of these todo)

const checkStorage = await AsyncStorage.getItem('@calendar')
if(checkStorage == 'true'){
    setFullCalendar(true)
} else if (checkStorage !== null){
    setFullCalendar(true)
} else{
    setFullCalendar(false)
}
2 Answers

Since it's only false if the value is null, just compare against that:

const checkStorage = await AsyncStorage.getItem('@calendar');
setFullCalendar(checkStorage !== null);

You could use double negation to eliminate falsey values like null, undefined, false, "", etc... and get the right boolean result, keep in mind that empty objects, and empty arrays are truthy, not falsey values.

setFullCalendar(!!(await AsyncStorage.getItem('@calendar')));

or use the Boolean object to get the boolean result of that async action

setFullCalendar(Boolean(await AsyncStorage.getItem('@calendar')))
Related