From f87b1d5d109dff1979520729c394ba0e345a66ee Mon Sep 17 00:00:00 2001 From: djmil Date: Tue, 14 Nov 2023 11:53:12 +0100 Subject: [PATCH] cleanup --- .../src/container/games/Message2Opponent.jsx | 50 +++++++------------ 1 file changed, 18 insertions(+), 32 deletions(-) diff --git a/webapp/src/container/games/Message2Opponent.jsx b/webapp/src/container/games/Message2Opponent.jsx index 1105e75..21dca32 100644 --- a/webapp/src/container/games/Message2Opponent.jsx +++ b/webapp/src/container/games/Message2Opponent.jsx @@ -1,62 +1,48 @@ -import React, { useContext, /* useEffect,*/ useRef, useState } from 'react'; +import React, { useContext, useRef, useState } from 'react'; import { useLocation, matchPath } from 'react-router-dom'; import { GamesContext } from '../../context/games'; -//import { useLocationChange } from '../../hook/Location'; export default function Message2Opponent({ dispatchGames }) { const games = useContext(GamesContext); - const [message2opponent, setMessage2opponent] = useState(''); const { pathname } = useLocation(); - const timeoutIdRef = useRef(null); + const [value, setValue] = useState(''); + const syncTimeoutRef = useRef(null); - if (timeoutIdRef.current === null) { - // sync: internal <- external - // Sync external and internsl states only in abnsence of a delay timer - console.log("check message", message2opponent); + if (syncTimeoutRef.current === null) { // <<--- Absorb external value if there is no scheduled sync if (matchPath('/games/new', pathname)) { - if (message2opponent !== games.newGame.message2opponent) - setMessage2opponent(games.newGame.message2opponent); - } - else - if (message2opponent !== '') { - setMessage2opponent(''); - } + if (value !== games.newGame.message2opponent) + setValue(games.newGame.message2opponent); + } else if (value !== '') { + setValue(''); + } } - console.log('timeout.current', timeoutIdRef.current) /* --- */ + const sync = (message2opponent) => { + syncTimeoutRef.current = null; - const delayedSync = (message2opponent) => { - timeoutIdRef.current = null; - - // sync: internl -> external if (matchPath('/games/new', pathname)) return dispatchGames({ type: 'nextNewGame', message2opponent }); console.warn('unknown path'); } - const onChange = (value) => { - setMessage2opponent(value); + const update = (value) => { + setValue(value); - if (timeoutIdRef.current) - clearTimeout(timeoutIdRef.current); // cancel previous sync + if (syncTimeoutRef.current) + clearTimeout(syncTimeoutRef.current); // <<--- Cancel previous sync - timeoutIdRef.current = setTimeout(() => delayedSync(value), 500); + syncTimeoutRef.current = setTimeout(() => sync(value), 500); } - - //var gpathname; - //useLocationChange(({ pathname }) => { - - return ( onChange(e.target.value)} + onChange={e => update(e.target.value)} /> ) } \ No newline at end of file