server side rendering - Next.js 14: useSuspenseQuery not triggering Suspense fallback on refresh - Stack Overflow

admin2025-04-15  0

When you navigate from the main page to the update page, Suspendse performs the fallback successfully, but after updating on the update page, fallback does not work.

// update/[id]/page.js
'use client'
import React, { Suspense } from 'react';
import ErrorBoundary from '../../components/ErrorBoundary';
import UpdateTopiceDataFetcher from '../../components/UpdatePage/UpdateTopiceDataFetcher';

const UpdatePage = ({ params: { id } }) => {
    return (
        <div className='updateCotainer'>
            <div className="updateForm">
                <ErrorBoundary fallback={<h2>Error!!!</h2>}>
                    <Suspense fallback={<h2>Loading...</h2>}>
                        <UpdateTopiceDataFetcher id={id} />
                    </Suspense>
                </ErrorBoundary>
            </div>
        </div>
    );
}

export default UpdatePage;

'use client'
import { useSuspenseQuery } from '@tanstack/react-query';
import fetchTopiceData from '../../utils/shared/fetchTopiceData';
import UpdateForm from './UpdateForm';

const UpdateTopiceDataFetcher = ({ id }) => {
    const { data: topiceData } = useSuspenseQuery({
        queryKey: ['topiceData', id],
        queryFn: () => fetchTopiceData(`${process.env.NEXT_PUBLIC_API_URL}api/topices/${id}`),
    });


    return <UpdateForm topiceData={topiceData} />;
};

export default UpdateTopiceDataFetcher;

I am using useSuspenseQuery from React Query in a Next.js 14 project.

I wrapped my component with <Suspense fallback={<div>Loading...</div>}>, expecting that when I refresh the page, the fallback would be displayed while the data is being fetched. However, after refreshing, the Suspense fallback is not triggered, and the page renders without showing "Loading...".

I tried:

  • Setting staleTime: 0 in useSuspenseQuery, but it did not solve the issue.
  • Setting cacheTime: 0 to ensure no cached data is used, but the fallback still does not appear.
  • Wrapping the entire page with <Suspense> to force loading behavior, but the issue persists.
  • Checking the network tab in Chrome DevTools, and I confirmed that a new API request is indeed being made after the refresh.
  • Using useEffect and useState to enforce CSR (Client-Side Rendering), which does work but is not an ideal solution. This approach forces client-side behavior, but it does not align with React Query's recommended pattern of handling loading and error states externally.
  • Using dynamic() with { ssr: false } to exclude the component from SSR, but this did not solve the issue either.

❗ What I Expected:

  • When I refresh the page, I expect Suspense to display the "Loading..." fallback until the API request completes.
  • However, the page renders immediately, skipping the fallback state.
转载请注明原文地址:http://www.anycun.com/QandA/1744715679a86624.html