-
Notifications
You must be signed in to change notification settings - Fork 93
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add helper to wrap state from other hooks? #57
Comments
An alternative way to handle this nicely would be to allow function Example() {
const [user, setUser] = useLocalStorage('user')
const [, updateUser] = useImmer(user, setUser)
updateUser(user => {
user.name = 'New Name'
})
} I think this is actually more flexible, so this would be the better solution. |
Hi Ian, Can you please update the Example component, I am not able to figure out what this component intends to do, and that will also help get more clarity about your issue. Thank you |
@ianstormtaylor I think I get what you are getting at. I think the first solution is nicer, the second one looks incorrect, as immer wouldn't receive the new However, I think this is a simpler solution that doesn't need new api's: import {produce} from immer
function Example() {
const [user, _setUser] = useLocalStorage('user')
const updateUser = useMemo(() => produce(_setUser), [])
updateUser(user => {
user.name = 'New Name'
})
} |
@mweststrate How would you implement such a thing using reducer? Edit - I have managed to do so with export function useCart() {
const [storageCart, setStorageCart] = useLocalStorage("cart", initalCart);
const [cart, dispatch] = useImmerReducer<Cart>(reducer, storageCart);
React.useEffect(() => {
setStorageCart(cart);
}, [cart, setStorageCart]);
return [cart, dispatch] as const;
} |
Running into a situation that I think would be nicely handled in
use-immer
since it seems somewhat common...If you a value is scoped to your component, then the current
useImmer
works well. But if you don't have control over the value (eg. it's passed from a parent, or it's gotten from local storage, etc.) then you have the deal with the annoyance of using a callback to set the new state.But it would be nice to be able to do something like:
Since the
[value, setValue]
pattern is widespread, this new hook would be very flexible and could be used to augment any existing tuple-returning state hook.What do you think?
The text was updated successfully, but these errors were encountered: