0

I want to use useSuspenseQuery along with next js so that I can take advantage of the built-in React feature.

But when using useSuspenseQuery, it gives an error img

query

const { data, isLoading } = useSuspenseQuery({
        queryKey: ["user"],
        queryFn: () => {
            return (userService.getUserById(Number(id)))},
    });

axios interceptor

axiosWithAuth.interceptors.response.use(
    (config) => config,
    async (error) => {
        const originalRequest = error.config;

        if (
            (error?.response?.status === 401 ||
                errorCatch(error) === "jwt expried" ||
                errorCatch(error) === "jwt must be provided") &&
            error.config &&
            !error.config._isRetry
        ) {
            originalRequest._isRetry = true;
            try {
                const { accessToken } = await authService.getNewTokens();

                originalRequest.headers[
                    "Authorization"
                ] = `Bearer ${accessToken}`;
                
                return axiosWithAuth.request(originalRequest);
            } catch (error) {
                if (errorCatch(error) === "jwt expired") removeFromStorage();
            }
        }

        throw error;
    }
);

query with axios

  async getUserById(userId: number) {
        const response = await axiosWithAuth<IUserTg>({
            url: API_URL.user(`/${userId}`),
            method: "GET",
        });
        return response.data;
    }

When switching between pages (when routing), it does not give such an error, but if you refresh the page itself, it will give

if you use use Query, then everything works as it should (but I need useSuspenseQuery) if you disable authorization verification on the server, then everything works fine, without errors (but I need the request to be authorized)

1 Answer 1

0

This is likely due to Next attempting to pre-render the Suspense boundary, despite the useSuspenseQuery falling under a client component (https://nextjs.org/docs/app/building-your-application/rendering/client-components) -- since the pre-render attempt is missing the client's headers/cookies, it is presumably failing your authorization.

Some notes on Suspense behavior with useSuspenseQuery can be found here: https://tanstack.com/query/latest/docs/framework/react/guides/ssr#a-quick-note-on-suspense.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.