In my react native app, users can favorite items which I store in AsyncStorage. I visually show this on the screen and keep track of that using useState variable. When the user navigates away and then comes back i use the useEffect hook and call AsyncStorage to validate if the item is a favorite. If true, I updated the useState variable. This works but when they return the favorites button shows the default (false) for a fraction of a second while the item is looked up in AsyncStorage, which is not optimal. Is there a way to avoid this delay ?
import React, { useState, useEffect } from "react";
//async storage functions
import storage from "../../utility/storage";
//count context for use in other screens
import { useCounter } from "../../contexts/FavoritesCountContext";
function ItemDetails(props) {
const [isFav, setIsFav] = useState(false);
const { increment, decrement } = useCounter();
const checkFavStatus = async () => {
try {
//name passed in through props
const fav = await storage.isFavorited(name);
setIsFav(fav);
} catch (error) {
console.log(error);
}
};
useEffect(() => {
checkFavStatus();
}, [isFav]);
async function handleFavorite() {
if (isFav) {
await storage.remove(name);
setIsFav(false);
decrement();
} else {
await storage.store(name);
setIsFav(true);
increment();
}
}
return (
<Screen>
<TouchableOpacity onPress={handleFavorite}>
<FavButton
name={"heart"}
size={250}
iconColor={isFav ? red : white}
backgroundColor={"transparent"}
/>
</TouchableOpacity>
</Screen>
);
}