For the purpose of learning I am trying to breakdown the basics of the flux pattern by implementing it from scratch. I know that I can fix the problem below using a Class Component but why does it work with the class component's setState({ ... }) and not with the hook's setValues function?
As you can guess, the problem is that the setValues function does not seem to trigger a re-render with the new state. I have a feeling this has to do with closures, but I don't understand them super well, so I would appreciate any guidance and help.
Store
// store.js
import EventEmitter from "events";
class StoreClass extends EventEmitter {
constructor() {
super();
this.values = []
}
addNow() {
this.values.push(Date.now());
this.emit('change')
}
getAll() {
return this.values;
}
}
const store = new StoreClass();
export default store;
Component
// App.js
import store from './store';
function App() {
const [values, setValues] = useState([]);
const handleClick = () => {
store.addNow();
};
useEffect(() => {
const onChangeHandler = () => {
console.log("Change called");
setValues(() => store.getAll())
};
store.on('change', onChangeHandler);
return () => store.removeAllListeners('change')
}, [values]);
return (
<div>
<button onClick={handleClick}>Click to add</button>
<ul>
{values.map(val => <li key={val}>{val}</li>)}
</ul>
</div>
);
}