Passing the optimistic value to an action #8
Unanswered
devongovett
asked this question in
Q&A
Replies: 1 comment
-
|
This is also an open question for me, I mentioned it here: "Who calls useOptimistic? The caller or the design component?" I don't see why you need the updater function here, I think that's really only needed if you have multiple events that could mutate the optimistic value - here you only have one How if your problem different to the like button example in the docs? https://react.dev/reference/react/useOptimistic#updating-props-or-state-optimistically They feel similar: calculate a new value based on the existing optimistic value, set the new value with |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm thinking about patterns for actions in React Aria. A common pattern in many components is an interface like this:
Internally, we use
useOptimisticto store the latest value to display to the user.Sometimes, we need to calculate
newValuebased on the previous state. I think this should be based on the optimistic value, not thevalueprop, because the optimistic value is what the user is seeing and they will expect the updated state to reflect that. We can do that by passing a function tosetOptimisticValue. Then ideally we'd pass that value tochangeActionso the parent component can respond to it. However, there doesn't seem to be a good way to do this.This does not work because the callback is not called until the next render:
This does not work because React will error that you can't trigger a re-render while rendering a different component (assuming the action sets state in the parent component):
Has anyone found a good pattern for this? In the past, we've tracked the current value in a ref and used this to calculate the new value instead of using the setState callback. This feels quite hacky because you have to reset the ref on the next render to match the value prop, which seems like exactly what
useOptimisticis supposed to handle. However because you can't get the actual optimistic value synchronously, there's not a good place to call the action.Beta Was this translation helpful? Give feedback.
All reactions