0

api:

export const feedsApi = createApi({
  reducerPath: 'feeds',
  tagTypes: ['Feeds'],
  baseQuery: fetchBaseQuery({
    baseUrl: 'http://localhost:5000',
  }),
  endpoints: (build) => ({
    getFeedsByPage: build.query<FeedType[], string>({
      query: (page = '1') => `feeds?_page=${page}`,
      providesTags: (feeds, error, arg) => {
        return feeds
          ? [
              ...feeds.map(({ id }) => ({ type: 'Feeds', id } as const)),
              { type: 'Feeds', id: 'LIST' },
            ]
          : [{ type: 'Feeds', id: 'LIST' }]
      },
    }),
  }),
})

component:

const FeedsPaginationPage: React.FunctionComponent<
  FeedsPaginationPageProps
> = () => {
  const [query] = useSearchParams()
  const page = query.get('page') ?? '1'
  const { isLoading, data: feeds, isFetching } = useGetFeedsByPageQuery(page,{
    refetchOnMountOrArgChange: true
  })

  console.log('>>>', isLoading, feeds, isFetching, page)

  return (
    <>
      {isLoading ? (
        'loading'
      ) : (
        <>
          <button
            className="btn btn-link"
            onClick={() => navigate(`?page=${+page - 1}`)}
          >
            previous
          </button>{' '}
          <button
            className="btn btn-link"
            onClick={() => navigate(`?page=${+page + 1}`)}
          >
            next
          </button>
        </>
      )}
    </>
  )
}

I.e. there are 100 feeds:

When I visit page<2> from page<1>, I get feeds always an array of page<1>'s data(10 records), but in the state tree, obviously there is no such data. When useGetFeedsByPageQuery("2") is called, the feeds should be undefined, I don't understand why .

Matt.Z
  • 602
  • 7
  • 19

1 Answers1

1

The hook will keep the previous data in data as long as it is loading the new data so you can display it without flickering to an empty screen for a split second. You can always check isFetching to see if the data is just being fetched and the displayed data might be stale, or access currentData instead of data.

phry
  • 35,762
  • 5
  • 67
  • 81