I am working on a NextJs application that use App Router. I ran into some problems when we wanted to use React Query instead of fetching in server components. I have made a file in app/utils/api.ts.
And I have client component which is going to use React Query to fetch data. When I try to use my getData function with React Query I get multiple error: Module not found: Can't resolve 'fs', 'dns', 'https2'. Which I assume has to do with the network javascript functions not being available in the browser. If I was using Page Router I could have used getServerSideProps, but with App Router I dont know if I'm able to use anything like that. Is it possible to get the data on the server side and use the function inside a React Query? Here I provided some example code:
import { DaprClient, HttpMethod } from '@dapr/dapr';
import { DataType} from '../models/Data';
const daprHost = '127.0.0.1'; // Dapr Sidecar Host
const daprPort = '3500'; // Dapr Sidecar Port of this Example Server
const client = new DaprClient({ daprHost, daprPort });
export async function getData() {
const serviceAppId = 'backendApi';
const serviceMethod = '/api';
try {
// GET Request
const response = await client.invoker.invoke(
serviceAppId,
serviceMethod,
HttpMethod.GET
);
return response as AvvikAPI;
} catch (err) {
console.log(err);
return undefined;
}
}
async function PageWithMUI() {
const { data, isLoading } = useQuery('key', getData);
}
import React from 'react';
import { DaprClient, HttpMethod } from '@dapr/dapr';
import {
Avvik,
AvvikAPI,
GrunnmurStatus,
getFakturaKilder,
} from '../models/Avvik';
import DropdownGrid from './components/DropdownGrid';
The fetching method down below works. I wrapped the Component in a Server Side Component, but since we are using MUI and MUI does not support Server Side Rendering. But this won't be ideal in the long run.
const daprHost = '127.0.0.1'; // Dapr Sidecar Host
const daprPort = '3500'; // Dapr Sidecar Port of this Example Server
const client = new DaprClient({ daprHost, daprPort });
export const revalidate = 60; // revalidate every minute
async function getData() {
const serviceAppId = 'backendApi';
const serviceMethod = '/api';
try {
// GET Request
const response = await client.invoker.invoke(
serviceAppId,
serviceMethod,
HttpMethod.GET
);
return response as DataType;
} catch (err) {
console.log(err);
return undefined;
}
}
async function Home() {
const data: DataType | undefined = await getData();
return (
<div className='flex min-h-screen flex-col pt-6 pl-[2.38rem] pr-[3rem] lg:pl-[3rem] bg-[var(--background)]'>
<h1 className='mb-[1.38rem]'>Grunnmuren - Status</h1>
<PageWithMUI data={data} />
</div>
);
}