✨ Save score in IndexedDB
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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]);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user