bcherny / undux

⚡️ Dead simple state for React. Now with Hooks support.
https://undux.org
MIT License
1.49k stars 31 forks source link

Can not update store in useEffect hooks function. #164

Open JayWang0 opened 8 months ago

JayWang0 commented 8 months ago

I want to listen to the property change, and then update the store, however it doesn't work. any workaround?

Here is my code: ` import React from 'react'; import Store from './MyStore';

// Re-render the component when the store updates.

function MyComponent() { let store = Store.useStore();

React.useEffect(() => { store.on('one').subscribe((one) => { console.log(store); store.set('sum')(store.get('one') + store.get('two')); });

store.on('two').subscribe((two) => {
  console.log(store);
  store.set('sum')(store.get('one') + store.get('two'));
});

}, []);

return (

Sum: {store.get('sum')}

); }

function NumberInput({ storeKey, value }) { let store = Store.useStore();

return ( <input onChange={(e) => store.set(storeKey)(parseInt(e.target.value, 10))} type="number" value={value} /> ); }

export default Store.withStore(MyComponent);

`

` import { createConnectedStore } from 'undux';

let initialState = { one: 0, two: 0, sum: 0, };

export default createConnectedStore(initialState);

`

JayWang0 commented 8 months ago

https://undux-readme-demo-js-mgnrwt.stackblitz.io