Replies: 4 comments
-
The optimistic UI should not trigger a revalidation, then you do the POST/PATCH/DELETE, and then you trigger a revalidation to ensure data is up to date. You must await for the DB update before you trigger the revalidation. This way your update will be up to date. |
Beta Was this translation helpful? Give feedback.
-
@sergiodxa |
Beta Was this translation helpful? Give feedback.
-
I haven't tried with the interval, but the focus is less likely to happen (the user must have to change tabs first), and even if SWR had already revalidated the data, if you manually trigger a new revalidation it will happen again, so you don't need to care if focus revalidation or interval revalidation happened before the DB was updated, and SWR will ignore the response of a pending request triggered before your manual revalidation. |
Beta Was this translation helpful? Give feedback.
-
I'm looking at writing hooks to wrap const { data, error, mutate } = useSWR('/api/users', () => API.fetchUsers())
const [createUserLoading, setCreateUserLoading] = useState(false)
const createUser = {
loading: createUserLoading,
error: cache.get(`error@createUser`),
apply: async (user) => {
try {
cache.set(`error@createUser`, undefined)
setCreateUserLoading(true)
mutate(
(userList) => userList.concat(user),
false // <-- important to make sure it doesn't try to revalidate immediately
)
const createdUser = await API.createUser(user)
} catch (e) {
cache.set(`error@createUser`, e)
} finally {
/* ALWAYS revalidate after an API call happens
because you want the API to be your source of
truth, not assume you can manipulate state to
keep in synch with the API */
mutate()
setCreateUserLoading(false)
}
}
return {
data,
error,
createUser
} Then the component can just: const { data: userList, error, createAction } = useUserList()
return (
// map of users => <tr><td>{user.name}</td></tr>
{createAction.error && <div className="error">Whoopsie!</div>}
<button
disabled={createAction.loading}
onClick={() => createAction.apply(/* some user object */)}
>Create a User</button>
) Probably should be using refs and not the cache for error-storing, but you get the idea |
Beta Was this translation helpful? Give feedback.
-
Hi,
I have a components of users reviews.
The component use useSWR to fetch the reviews.
The user can delete/edit a review.
After the user delete/edit a review, I use mutate to update the cached version.
How can I avoid the following scenario?
Even if in step 2 I call mutate with false param (do not revalidate), swr possibly can revalidate again depends on the options param.
How can I avoid this scenario? What is the best practice for optimistic UI? thanks!
Beta Was this translation helpful? Give feedback.
All reactions