tonsz

using localStorage

docs

implementation for state management

💡 the main goal is to let data persist for a trivia game. the problem is player progress is lost whenever the window is refreshed. using just html, css and jquery.

two functions are created to be called whenever there is a need to set or get data from localstorage, respectively.

function saveState(state) {
  const stateString = JSON.stringify(state);
  localStorage.setItem("state", stateString);
}

function getState() {
  const stateString = localStorage.getItem("state");
  const state = JSON.parse(stateString);
  return state;
}

example:

let state = getState();
const initialState = {
  game: {
    money: 0,
    stars: 3,
    answered: [],
  },
};

saveState(initialState);

initializing the game

the app now has the means to remember if a game is currently ongoing or not. say, the app must show a welcome message and click a button to initialize the game. before, the game just immediately lays out the board for the player. now, we can check first if there is an ongoing state in local storage.

function init() {
  if (!localStorage.getItem("state")) {
    welcome(); // the initialState is set here
  } else {
    startGame();
  }
}

init();

wrap-up

before involving localstorage, the variables for the players' money, number of stars and answered questions are stored only in variables. this would result to the game restarting back to its initial state. now that the data is stored, all variables are replaced with instances of the state that was assigned from the getState method. and each time the player does something to manipulate the variables, saveState is called.

of course, this is only really slightly better - the code is messy and spaghetti as it is. the only real solution is to use a framework. meanwhile, through this i ended up doing further readings on cloning objects in js.

#jeoparrdy #notes #web