I am trying to show the number of each item in Drawer Item in react native. for this purpose I created a function which returns the number of items I want. But it does not give me what I want. How can I call this function in Drawer Item title?
function:
const countItems = async () => {
const storedArray = await AsyncStorage.getItem('fav_data').then(favs => {
const count = JSON.parse(favs).length;
return count;
})
// console.log(storedArray)
return storedArray;
}
and here I want to call it:
<DrawerItem title={'test ' countItems()} accessoryLeft={HeartIcon}
onPress={() => navigation.navigate('Favorites')}/>
CodePudding user response:
You're not await
ing the result of countItems, so it will return undefined
at render time. Since the number isn't stored in state, changes to the number won't trigger a re-render of the screen.
Here's an example of the most common way to solve this problem: with state and effect hooks.
const [count, setCount] = useState();
useEffect(() => {
AsyncStorage.getItem('fav_data').then(favs => {
const count = JSON.parse(favs).length;
setCount(count);
})
}, []);
...
<DrawerItem
title={count ?? 'Loading'}
accessoryLeft={HeartIcon}
onPress={() => navigation.navigate('Favorites')}
/>
The useEffect hook has an empty dependency array (the 2nd argument), so it will only run once, on the mount of the component.
If you want to read more about the state and effect hooks, sections 3 and 4 of the following React doc have good explanations: https://reactjs.org/docs/hooks-intro.html