Skip to content

Commit

Permalink
Save the sessionId clientside
Browse files Browse the repository at this point in the history
We need a way for users to reconnect to their serverside session if
their connection drops or they leave the page and return.
We use sessionStorage so that the session is not shared across tabs as
it would be for localStorage.
We receive the "session:set" event from the server which tells us the
server has save the session and now it's time for the client to do the
same.
We use the "DOMContentLoaded" event to attempt to read the sessionId
from localStorage, if it exists then we connect. If it doesn't exist the
user will have to manually connect by entering their name.

Co-authored-by: Ynda Jas <ynda@dxw.com>
Co-authored-by: George Eaton <george@dxw.com>
Co-authored-by: Liz Daly <liz.daly@dxw.com>
  • Loading branch information
4 people committed Sep 18, 2024
1 parent 0d1e018 commit 6b3c533
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,27 @@ socket.on("scoresAndBonusPoints:get", (playerScores, bonusPoints) => {
renderBonusPoints(bonusPoints);
});

socket.on("session:set", (session) => {
socket.auth = { sessionId: session.id };
sessionStorage.setItem("sessionId", session.id);
});

const nameFormElement = getElementById<NameFormElement>("name-form");

const roundResetButtonElement =
getElementById<HTMLButtonElement>("round-reset-button");

const startButtonElement = getElementById<HTMLButtonElement>("start-button");

window.document.addEventListener("DOMContentLoaded", () => {
const sessionId = sessionStorage.getItem("sessionId");

if (sessionId) {
socket.auth = { sessionId };
socket.connect();
}
});

nameFormElement.addEventListener("submit", (e) => {
e.preventDefault();
addPlayer(socket, nameFormElement.elements.name.value);
Expand Down

0 comments on commit 6b3c533

Please sign in to comment.