Next.js Discord

Discord Forum

I am trying to use react-query on server components

Unanswered
American Pipit posted this in #help-forum
Open in Discord
American PipitOP
I am trying to use react-query in server components, however, I am running into an issue. I have a JobList component that uses a useJobs hook:
 const JobList = async () => {
    const { jobs } = useJobs();

    return (
        <div className='overflow-y-scroll h-[80%]'>
            {jobs?.map((job) => (
                <JobPost job={job} />
            ))}
        </div>
    );
}; 


The useJobs hook has a react-querys hook useQuery which fetches a list of jobs from supabase using
createServerComponentClient
, which then refetches the results based on filters provided. The hook looks like this:
 const useJobs = (filters?: string[]) => {
    const { data: jobs, ...rest } = useQuery(['jobs', filters], () =>
        getJobs(filters)
    );

    return { jobs, ...rest };
}; 
and the getJobs() function looks like this:
 export const getJobs = async (filters?: string[]) => {
    if (!filters) {
        const { data: jobs, error } = await supabase
            .from('job_details')
            .select('*');

        if (error) throw error;

        return jobs;
    }

    const { data: jobs, error } = await supabase
        .from('job_details')
        .select('*')
        .eq('job_time', filters);

    if (error) throw error;

    return jobs;
}; 
. How do I fix the
createContext only works in client components
error? When I switch to client component, I get an async/await doesn't work in client components error. I still don't have deep understanding of the concepts that wrap this, and I feel that I have an issue in core knowledge. Is using useEffect to set state and then exporting it (not using react-query) a solution to this? This is how I would do it before, but I liked the options that react-query provides.

3 Replies

simple way to understand is like this: there are multiple servers(instances) are up and running, especially Vercel serverless platform, you cannot expect requests from the same client are handled by the same instance. thus state cannot be managed by custom hooks so it is not allowed. As for client side, users use their own web browser(tab), so you can keep states in JS global variables so SPA does.
basically React rendering are sync func. Vercel recently introduced progressive server side rendering with async and suspense, but it does not work in client components. useEffect is kinda escape hatch as you said.
as to fetch cache, you might want to read this.
https://vercel.com/blog/vercel-cache-api-nextjs-cache