Skip to content

State in JS process

Course: Singleton Pattern, Backend State management and Pub Subs - chapter 3

How/where can you store state in a Javascript process

This state might being used by multiple files, not just one, so the following approach might not work

Lets try the following -

  • index.ts - pushes to games array
import { games } from "./store";
import { startLogger } from "./logger";
startLogger();
setInterval(() => {
games.push({
"whitePlayer": "harkirat",
"blackPlayer": "jaskirat",
moves: []
})
}, 5000)
  • logger.ts - uses the games array
import { games } from "./store";
export function startLogger() {
setInterval(() => {
console.log(games);
}, 4000)
}
  • store.ts - Exports the game array
interface Game {
whitePlayer: string;
blackPlayer: string;
moves: string[];
}
export const games: Game[] = [];

This will work, but a lot of times you need to attach functionality to state as well.

Let’s see how can we create a class called GameManager and expose some functions on it that can be called by files using it

💡 There are other ways of storing state in a TS project as well, redux being a popular one. Yes, you can use redux in the backend as well