I am still trying to wrap my head around this scenario. Can anyone please suggest what is the correct way to do this in Next.js 13?
I diplay a list of users in a Server Component, for example, like this (using MongoDB):
// UsersList.jsx
const UsersList = () => {
const users = await usersCollection.getUsers()
return (
<div>
{users.map(user) => <div>{user}</div>}
</div>
)
}
And on the same page, I have also defined client component for adding users:
// UsersEdit.jsx
'use client'
const UsersEdit = () => {
const handleAdd() => // calls POST to /api/users
return // render input + button
}
Both are displayed together like this in a Server Component Page:
// page.jsx
const Users = () => {
return (
<div>
<UsersList />
<UsersEdit />
</div>
)
}
How should I "reload" or "notify" UsersList
that a new user has been added to the collection to force it to display a new user/updated user?
2
Answers
For now, the only way to have the updated data by your Client Component reflected on the Server Component is to call
router.refresh()
, whererouter
is the returned value byuseRouter
, after your request to the API. As you can read on the official Next.js doc:And they gave a wonderful example, working with a Todo List application. I added it below to have a more complete thread.
https://stackoverflow.com/a/75127011/17964403
This is Great for mutating on the client side but if you want to do something like search/filtering using input on the client side and want to re-fetch the same data you can do something like
and in the server component, you will receive the search param as a prop, see if the search param exists, if so then in the fetch call pass that and you will get filtered items.