Next.js Discord

Discord Forum

How to revalidate a client page that is getting data from server action ?

Answered
Tan posted this in #help-forum
Open in Discord
TanOP
I am using server-action to fetch data and send it to client component.

  const [products, setProducts] = useState<Product[] | null>();
  const [query, setQuery] = useState("");

  // Fetch data and store in products
  useEffect(() => {
    getAllProducts().then((p) => setProducts(p));
  }, []);

And I am saving it in state. How can I revalidate here after I delete a product or edit a product ?

OR
Is there better way ? I want client side interactive to be able to filter the list. That's why I am using client component. If there is better way to implement live search functionality using server component that will be better.
Answered by joulev
don't use server actions for things like this. just run getAllProducts (without the "use server") in a server component then pass the data to this client component as a prop
View full answer

14 Replies

TanOP
I have implemented a workaround.
  const [render, reRender] = useState(false);
  const [products, setProducts] = useState<Product[] | null>();
  const [query, setQuery] = useState("");

  // Fetch data and store in products
  useEffect(() => {
    getAllProducts().then((p) => setProducts(p));
  }, [render]);

I will just update render function if there will be any changes in data from client side. I don't know if it is the optimal solution.
European anchovy
in your serverfunction you can use revalidatePath("/yourpath"); or revalidateTag if you set a tag to your products for examply with const res = await fetch('https://...', { next: { tags: ['products'] } }), then you can do revalidateTag('products'). Or you can set a timer to revalidate every x amount of senconds.
European anchovy
you want to revalidate it in the client?
you can use the useRouter
const router = useRouter();

router.refresh();
it will revalidate your data.
@European anchovy javascript const router = useRouter(); router.refresh();
TanOP
It seems interesting. I will try it. Thank you !!
European anchovy
you can put the router.refresh in your useEffect for example
Cape lion
another way could be to set up a helper server action that is passed an array of tags, each to be revalidated. This way the client doesn't have to refresh the entire page.
Answer
from there you can use router.refresh or revalidateTag or revalidatePath to revalidate the route