skip to Main Content

I’ve modifying some existing React Native code where I’ve to check if network connection is available or not. If it is available, I’ve to fetch new data from API, otherwise I’ve to use cached data. This is what I’ve achieved so far:

export const useStudentData = (
  studentId: Student['id']
): UseQueryResult<Student, Error> => {
  
    const queryKey = studentDataKeys.list({ studentIdEq: studentData?.id });
    const queryClient = useQueryClient();
    const {isConnected} = useNetInfo();
  
    if(!isConnected){
      // return previously cached data here
    }
  
    const data = useQuery<Student, Error>(
        studentDataKeys.detail(studentId),
      async () => {
        const { data: student } = await StudentDataAPI.fetchDataById(studentId);
  
        return StudentData.deserialize({
          ...studentData,
          assignments: studentData.assignments?.filter((assignment) => assignment.submitted)
        });
      },
      {
        staleTime: 1000 * 60 * 60 * 10,
        retry: 0,
        initialData: () => {
          const previousStudentData = queryClient.getQueryData<Student[]>(queryKey);
  
          return previousStudentData?.find((studentData) => studentData.id === studentId);
        },
        initialDataUpdatedAt: queryClient.getQueryState(queryKey)?.dataUpdatedAt,
        onError() {
          console.log("Error with API fetching");
        }
      }
    );
  
    return data;
  };

How can I modify it so that if network connection is present, it should download new data otherwise return previous/old data that was cached in previous successful call?

3

Answers


  1. You can rely on the queryKey for that. In detail, react-query caches the result based on the key.
    Your current key is studentDataKeys.detail(studentId), what about replacing it with [studentDataKeys.detail(studentId), isConnected]?

    Login or Signup to reply.
  2. Instead of reinventing the wheel, you can use the existing solution. That is:

    import NetInfo from '@react-native-community/netinfo'
    import { onlineManager } from '@tanstack/react-query'
    
    onlineManager.setEventListener(setOnline => {
      return NetInfo.addEventListener(state => {
        setOnline(!!state.isConnected)
      })
    })
    

    After implementing this, react-query will automatically refetch your data when the device is back online.

    Login or Signup to reply.
  3. You’re trying to implement a feature that React-Query provides to you for free.

    React-Query will keep displaying old data until new data is available. By default, React-Query will stop trying to fetch data entirely until you are back online.

    Additionally, you can set the refetchOnReconnect flag to true (which is also the default) in order to request fresh data the moment you are online.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search