How to properly refetch data when reloading in any page?

Viewed 218

So I am fetching data from my backend on a landing page in my app. This data is used in different parts, so I use redux for global state. The code is something like this:

//Landing Component
export default function Landing() {
    const data = useSelector(state => state.data);
    useEffect(() => {
        if (!data.isAvailable) {
            fetchData();
        }
        ...
    }, [])
    ...
}

//Some Component
export default function SomeComponent() {
    const data = useSelector(state => state.data)
    ...
}

//Another Component
export default function AnotherComponent() {
    const data = useSelector(state => state.data)
    ...
}

However as we know, if the user refreshes the page, the data stored in redux is re-initialized. The problem is, if the user refreshes while on the other pages, data does not get refetched. So what I do is I repeat the same useEffect in every other component that needs the data in order to refetch it in the event the user reloads in a different page.

//Some Component
export default function SomeComponent() {
    const data = useSelector(state => state.data)
    useEffect(() => {
        if (!data.isAvailable) {
            fetchData();
        }
        ...
    }, [])
    ...
}

I'm sure there are better ways to do this. I've heard of persisting data through localStorage or using redux-persist. But this data can become quite large so I don't think localStorage will do. Something like a global useEffect that will rerun whatever page the user may be. Thank you!

1 Answers

There is one problem with your approach of calling fetchData in useEffect. If you extend it to multiple components you would end up calling fetchData multiple times.

There isn't a silver bullet solution for this problem. However, one reusable solution would be to dispatch an initializer action and listen in the required reducer using an async thunk and hydrate its own store properties.

Related