NextJS Server Component not updating API data?
Hey people,
I am relatively new to NextJS (using the AppRouter) and currently have the following problem:
Overview:
I have a server component that should display a list of items. These items are loaded from an external backend using axios.
I also have a form (on another page) that I can use to add new items.
Problem:
If I add a new item (whether via the form or directly in the database) and then navigate (or am redirected) to the page with the list, I don't see the new items.
I first have to perform a full reload via the browser so that the new data is loaded from the backend.
My question:
Am I too stupid to use the server component correctly or is it simply wrong to use server components for such a scenario and I should just use client components.
Relevant code:
const client = axios.create({ baseURL: " http://localhost:9999 " }) async function getItems(): Promise<Item[]> { return client.get("/items") .then(response => response.data.items) .catch(error => { console.log(error); }); } const ItemsList: FC = async () => { const items = await getItems(); return ( <> // rendering list </> ); }; export default ItemsList;
Regards, Jannick (L1nd)
A server-side component is rendered only when loading the page. If there are changes, a reload of the page is required.
You can integrate client-side components within your server-side component. For example, your list entries. On the one hand, this would have the advantage that you could manipulate them in the browser directly (via events) and on the other hand you can use the client-side component and useRouter (router.refresh) request updated data from the server without having to reload the page.
Great, thank you. Then I simply make a client component from the list that retrieves the entries via useEffect from the API. That should be enough, because this is done every time during initial rendering.
This is the way