I've tried searching for an answer for this but I think I am missing something, tried searching for "call function in variable" without any luck. (Any tips on what I should've searched for are also welcomed!)
Anyways, I would like some clarification of how the code below works!
function createStore() {
let state = []
const getState = () => state
const dispatch = (action) => {
state = state.concat([action])
}
return {
getState,
dispatch
}
}
const store = createStore()
store.dispatch(1)
store.dispatch(2)
So, if i run store.dispatch(1) and then again store.dispatch(2) as above and then run store.getState, I get an array of [1, 2].
What I don't really understand is how these dispatches are stored?
I understand that they are saved within the state variable of the function, but shouldn't the function reset itself after being called?
It must be a local scope and only accessible via the function?
Are there any other way of accessing the state without calling getState?
Still learning JavaScript, so any clarification on this would be super!