Home > Blockchain >  How to prevent loading state in Redux toolkit if the data has already been fetched
How to prevent loading state in Redux toolkit if the data has already been fetched

Time:10-27

I want to stop showing the loading state if the data has been fetched, for example, if a user visits profile page, and move to another page, say Dashboard home if the user returns to the profile page, I don't want to show the loading state again.

This is how I'm fetching the data

 const { status, data } = useSelector((state) => state.profile);

  useEffect(() => {
    dispatch(fetchProfile());
  }, [dispatch]);

and if status === loading, I show the loader, and if fulfilled, I show the data

The Reducer

 builder.addCase(fetchProfile.fulfilled, (state, { payload }) => {
      state.profile.status = 'fulfilled';
      state.profile.data = payload.data;
    });

    builder.addCase(fetchProfile.pending, (state) => {
      state.profile.status = 'loading';
    });

    builder.addCase(fetchProfile.rejected, (state) => {
      state.profile.status = 'error';
    });

CodePudding user response:

you can implement it by either checking the data before calling the API or checking whether data is already there in API pending state

Method 1 Checking the data before calling the API

Call API only one time (in this method API won't call again and data won't be refreshed)

  const { status, data } = useSelector((state) => state.profile);

  useEffect(() => {
   if(!data) { //You can additionally check `data.userId` if needed
     dispatch(fetchProfile());
   } 
  }, [dispatch]);

Method 2 checking whether data is already there in API pending state

in this method, data will be updated in the background without showing loading

Check whether data is already there or not in the pending state.

  builder.addCase(fetchProfile.pending, (state) => {
      state.profile.status =  state.profile.data ? 'loading' : 'Data is already loaded';
    });
  • Related