React Native setting default value in setState

Viewed 1486
const getData = async (key) => {
        try {
        const jsonValue = await AsyncStorage.getItem(key)
        return jsonValue != null ? JSON.parse(jsonValue) : null;
        } catch(e) {
        console.log(e);
        }
    }

    useEffect(() => {
        setYoutube(getData('youtube'));
    }, []);

Im getting the data for the storage, but when there is no data stored I want to have the value set to FALSE,

I want it like setYoutube(getData('youtube')) when getData('youtube') has no value, I want it to be false

1 Answers

In your functional component :

[youtubedata,setYoutubedata] = useState(your_default_value_here)

Check here the api reference for useState

ps: you better change the name of your variable from setYoutube to setYoutubeData

Otherwise your doing it right here:

 return jsonValue != null ? JSON.parse(jsonValue) : null;

so if there's no data the default value is null but it's better to move your logic in the useState function

Related