Make React Query return previous data on error

Viewed 1243

Is there a way in React Query to return previous data when error occurs? Right now when there is error all posts disappear and I have empty page because data is undefined but I want to keep the old data. I want to have old data when error occurs. I have keepPreviousData: true but this doesn't solve the problem.

import React from 'react';
import AxiosClient from 'api/axiosClient';
import { createFetchResourcesAction } from 'api/actions/resources/resourcesActions';
import { Post, Resources } from 'api/actions/resources/resources.types';
import { Home } from './Home';

export const HomeContainer = () => {
  const { selectedPage, perPage, handlePageChange } = usePagination();

  const fetchResources = ({ pageParam = 1 }) =>
    AxiosClient.request<Resources<Post>>(createFetchResourcesAction(perPage, pageParam));

  const { data, isError, isFetching } = useQuery(
    ['resources', selectedPage, perPage],
    () => fetchResources({ pageParam: selectedPage }),
    { keepPreviousData: true },
  );

  return (
    <Home
      posts={data?.data.results}
      isLoading={isFetching}
      isError={isError}
      selectedPage={selectedPage}
      numberOfPages={Math.ceil(resolverNumberOfPages())}
      onPageChange={(action, value) => handlePageChange(action, +value)}
    />
  );
};

Home.tsx

import React from 'react';
import { useLocale } from 'hooks';
import { AppMessages } from 'i18n/messages';
import { Post } from './post/Post';
import { Box, Typography } from '@material-ui/core';
import { useStyles } from './Home.style';
import { HomeProps } from './Home.types';
import { Loader, ErrorMessage, Button } from 'ui';
import { Pagination } from 'ui';

export const Home = ({
  posts,
  isLoading,
  isError,
  numberOfPages,
  selectedPage,
  onPageChange,
}: HomeProps) => {
  const { formatMessage } = useLocale();
  const styles = useStyles();

  const handlePageChange = (page: number) => {
    onPageChange('page', page);
  };

  const postList = <>{posts && posts.map(post => <Post post={post} key={post.id} />)}</>;

  return (
    <Box className={styles.home}>
      <Box className={styles.main}>
        <Typography variant="h2" className={styles.title}>
          {formatMessage({ id: AppMessages['home.allEntries'] })}
        </Typography>
        <Box className={styles.postsWrapper}>
          {posts && posts.length < 1 && !isError && !isLoading && (
            <Typography variant="h3" className={styles.genericMessage}>
              {formatMessage({ id: AppMessages['home.noEntries'] })}
            </Typography>
          )}
          {postList}
          {isLoading && <Loader position="fixed" width={60} height={60} />}
          {isError && (
            <ErrorMessage position="top" description={formatMessage({ id: AppMessages['home.errorLoadingEntries'] })} />
          )}
          {isDesktop && numberOfPages > 1 ? (
            <Pagination numberOfPages={numberOfPages} selectedPage={selectedPage} onPageClick={handlePageChange} />
          ) : (
           nyll
          )}
        </Box>
      </Box>
    </Box>
  );
};

createFetchResourcesAction.ts

import { AxiosRequestConfig } from 'axios';

export const createFetchResourcesAction = (perPage: number, page: number): AxiosRequestConfig => {
  return {
    method: 'get',
    url: /resources?per_page=${perPage}&page=${page},
  };
}
1 Answers

As far as I'm aware, react-query doesn't delete any data from the cache if a query goes from success to error state. if you have data in your cache, you will get it, even if the query errors after that. So this is a possible state:

{ state: 'error', isError: true, data: { json from previous successful response }}
Related