Skip to content
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

addition to docs #120

Open
nonopolarity opened this issue Sep 13, 2023 · 1 comment
Open

addition to docs #120

nonopolarity opened this issue Sep 13, 2023 · 1 comment

Comments

@nonopolarity
Copy link

nonopolarity commented Sep 13, 2023

I am not too familiar with useReducer yet, but it seems useImmer can support

setCount(c => c + 1) or setToggle(t => !t).

The current README doesn't say this but just say setCount(count + 1).

Also, the way to think about

updateData(draft => {
  draft.foo.bar.num += 10;
});

is just like

setData(data => {
  const newData = deepCopy(data);
  newData.foo.bar.num += 10;
  return newData;
});

not exactly that, I think, because I noticed while debugging you don't always do a deep copy if you don't need to.

So the rule seems to be: it is as if you do a deep copy, and then you can "mutate" it like there is no tomorrow with that new copy, and then setData(newData). That may be an easy way to think about. Maybe you can add it to the README if it can help some users.

@Seize-cf
Copy link

Seize-cf commented Nov 2, 2023

If you want to make this feature work, you gotta use Proxy and Reflect to update the value of the state in the set method.

const [value, setValue] = useState<T | undefined>()

const createProxy = (target: T): T => {
  return new Proxy(target, {
    get: Reflect.get,
    set: (target, key: keyof T, value, receiver) => {
      target[key] = value
      setValue(createProxy(target))
      return Reflect.set(target, key, value, receiver)
    }
  })
}

Update: ahooks now has a handy function called useReactive that you can refer to.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants