How to display 404 error page with react-query in next-ssr

Viewed 286

I am using react query as stated in the doc

But, I am not sure how to return {notFound: true} from getServerSideProps. Could anyone help me how to handle this?

My code ins getServerSideProps is:

const queryClient = new QueryClient();
    await queryClient.prefetchQuery('amenities', () => getAmenities(params?.id as string));
    return {
      props: {
        dehydratedState: dehydrate(queryClient),
      },
    };

Now, what I want to do is, if the response is 404, then return 404 from getServerSideProps.

Update: I was not able to find any solution so removed react query in getServerSideProps. Now I'm fetching the data normally.

1 Answers

what you can do is do it on the client side.

const { data, isLoading, isError } = useQuery(
      ["amenities", router.query.id],
      () => getAmenities(router.query.id)
)
if(isError) router.push('404');

You can do it in the server side too

const queryClient = new QueryClient();
const data = await queryClient.prefetchQuery('amenities', () => getAmenities(params?.id as string));

if (!data) {
    return {
        notFound: true,
    }
} 

return {
  props: {
    dehydratedState: dehydrate(queryClient),
  },
};
Related