Next.js Discord

Discord Forum

Best way to handle loading/saving state with revalidate path

Unanswered
Plott Hound posted this in #help-forum
Open in Discord
Plott HoundOP
Lets use the example of a todo list.

1. User enters data to an input
2. User clicks a button to submit data
3. Set loading state to true.
4. Start a try/catch to perform a db operation to save the data.
5. server action is successful
6. we use revalidatePath to fetch the updated info.
7. server action responds with success so our try catch can set the loading state to false and fire a toast etc.

I always get a short delay between the server action's success response and the time it takes revalidate path and any fetching to reflect the updated data in the UI.

How can i handle this delay? ideally i want to set the loading state to false once the fetch is complete after we revalidatePath.

3 Replies

Plott HoundOP
The only solution i can think of is some kind of optimistic update. eg:
const handleDeleteDescription = async () => {
    const response = await handleDeleteTaskDescription(payload);

    if (response.success) {
        toast.success(response.message);
        //Update a local state for the description field so the change is immediately reflected in the UI
    } else {
        toast.error(response.message);
    }
};


But if I do this how can i make sure the data is in sync when the updated fetched data is ready? I'd rather not use a useEffect to update the state when the fetched object changes
Plott HoundOP
That’s a great call. Let me try it out