This is a really simple way to do global state in react

Home   »   This is a really simple way to do global state in react

import EventEmitter from 'eventemitter3'

export enum SimpleStoreEvents {
  change = 'change'
}

export class SimpleStore {
  constructor(storeName: string, state: T) {
    this._state = state
    this._storeName = storeName
    this._hydrate()
  }
  private _hydrate() {
    if (typeof window === 'undefined') return
    this._storeKey = `simple_store_${this._storeName}`
    try {
      const json = localStorage[this._storeKey] as string
      json && this.setState(JSON.parse(json) as T) 
    } catch (err) {
      console.error(err)
    }
  }
  private _storeKey: string
  private _storeName: string
  private _ee = new EventEmitter()
  private _state: T
  public get state() {
    return this._state
  }
  public setState(state: Partial) {
    this._state = { ...this._state, ...state }
    localStorage[this._storeKey] = JSON.stringify(this._state)
    this._ee.emit(SimpleStoreEvents.change)
  }
  public onChange(fn: () => void | (() => Promise)) {
    this._ee.on(SimpleStoreEvents.change, fn)
  }
  public offChange(fn: () => void | (() => Promise)) {
    this._ee.off(SimpleStoreEvents.change, fn)
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *