Maintaining a Store

Look at code to maintain a store in this lesson.

One problem with a reducer on its own is the possibility that different callers to the reducer might get out of sync. A solution to that is to also maintain a store. For our purposes here, a store is a centralized object that manages access to both a single source of central data and a related reducer. For our coin example, a store might look like this:

export class CoinStore {
  static state = {count: 0, value: 0}
  static getState(): { return state }
  static dispatch(action) {
    CoinStore.state = reducer(CoinStore.state, action)
    return CoinStore.state
  }
}     

Again, we’re holding off on TypeScript annotations. This code sets up a store with a single point of access:

CoinStore.dispatch({type: "AddPenny"}) 
CoinStore.dispatch({type: "AddNickel"})
const finalState = CoinStore.getState() 

In this case, you know that your return value from dispatch is the current state, but typically you only ask for the state explicitly, otherwise, you act on it only through actions.

Okay, what does that look like in our actual store, and how can we use TypeScript to help us make sure we get all the details right?

The store in TypeScript

Here’s what our store looks like in TypeScript:

Get hands-on with 1200+ tech skills courses.