Save score in IndexedDB

This commit is contained in:
2024-02-18 15:17:23 +01:00
parent 8219634b9c
commit 2b29a8e4b2
6 changed files with 69 additions and 6 deletions
+19 -1
View File
@@ -3,18 +3,36 @@
// ---------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------- Styles --------------------------------------------------------
import { useRef } from 'react';
import { useEffect, useRef } from 'react';
import './styles.scss';
import { useRecoilState } from 'recoil';
import { gameStateAtom } from '../../contexts/gameState';
import localforage from 'localforage';
// ---------------------------------------------------------------------------------------------------------------------
const store = localforage.createInstance({
name: 'leaderboard',
driver: localforage.INDEXEDDB,
version: 1.0,
storeName: 'leaderboard',
description: 'Store 10 best game time',
});
const Home = () => {
const difficultyRef = useRef<HTMLSelectElement>(null);
const sizeRef = useRef<HTMLSelectElement>(null);
const [, setGameState] = useRecoilState(gameStateAtom);
useEffect(() => {
const initIDB = async () => {
if ((await store.getItem('leaderboard')) === null) {
await store.setItem('leaderboard', []);
}
};
initIDB();
}, []);
const onClick = () => {
if (difficultyRef.current !== null && sizeRef.current !== null) {
const difficulty = difficultyRef.current.value;
+2 -3
View File
@@ -39,9 +39,8 @@ const LeaderBoard = () => {
useEffect(() => {
const getData = async () => {
const storeData = await store.getItem<LeaderBoardItem[]>('leaderboard');
if (storeData) {
setData(storeData);
}
setData(storeData || []);
};
if (data.length === 0) {
+3
View File
@@ -11,6 +11,7 @@ import Clock from '../../../assets/clock';
import '../styles.scss';
import { useRecoilState } from 'recoil';
import { gameStateAtom } from '../../../contexts/gameState';
import { saveToLocalStorage } from '../../../utils/generics';
// ---------------------------------------------------------------------------------------------------------------------
const Timer = () => {
@@ -53,7 +54,9 @@ const Timer = () => {
...prev,
gameTime: displayedTime,
}));
clearInterval(intervalId);
saveToLocalStorage(displayedTime);
}
}, [intervalId, gameState.endType, setGameState, displayedTime]);