Issue
I have a component that is using useFocusEffect hook to fetch data from AsyncStorage when the router goes back to this component.
const [carNames, setCarNames] = useState([]);
useFocusEffect(() => {
async function getCarNames() {
const cars = await AsyncStorage.getAllKeys();
setCarNames(cars);
}
getCarNames();
})
This is causing an infinite loop, the function getCarNames
is called over and over again. If I comment setCarNames(cars)
out the infinite loop stops, so it looks like every time the component is rendered this hook invokes the function. How to avoid this? I thought that this hook only invokes the function when route is "focused".
Solution
I'm not sure if Expo is simply re-exporting the hook from React Navigation, or if they have rolled their own version, but this would be expected behavior when using the React Navigation useFocusEffect. Their docs note that you need to wrap the inner function in a useCallback, or else it'll redefine the inner function on every render. Try:
useFocusEffect(
React.useCallback(() => {
async function getCarNames() {
const cars = await AsyncStorage.getAllKeys();
setCarNames(cars);
}
getCarNames();
}, [])
);
https://reactnavigation.org/docs/use-focus-effect/
Answered By - Abe
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.