I work on a order based overview based on the ID.
My structure looks like this
app
| page.tsx
| layout.tsx
| [id]
| | layout.tsx
| | dashboard
| | | page.tsx
| | purchases
| | |...
| api
| | getOrderData/[orderData]
...
The start page in "app" is filled with a component to fill the url with an id so that i get redirected to the dashboard.
Now I want to use an API to fetch my data per page, so that I have optimized loading.
Every page (dashboard, purchases, …) has its own API Call, which needs to run whenever my orderNo in inputted (start page) or changed (within my header in dashboard)
But because I currently need the id from my url, so useParams(), the page needs to be a client component, which clashes with fetch calls.
I know about useEffect(), but is there a better way to fetch my calls on loading or do I have to put useEffect in every page?
And, last question for now, should i load the whole page or suspense only the parts that are displaying the data?
Thanks in advance
export default function dashboard() {
const [data,setData] = useState<cards[]>([])
const params = useParams<{ orderNo: string }>();
const { orderNo } = params;
useEffect(()=>{
async function loadData(){
const res = await fetchData(orderNo)
setData(res)
}
loadData()
},[orderNo])
return ... }
This is the code im using now. fetchData is just another function in my lib to talk to my local API route
<CardsDisplay cards={data} />
That is my component that will display the data.
2
Answers
To fetch data from the client within the context of a React component,
useEffect
is pretty much your only option (or one of the many libraries that essentially derive from this e.g.react-query
)Look likes you are using Next.js version 14 with App Router. You can retrieve
id
fromparams
prop directly in server.References: