Next.js Discord

Discord Forum

Infinite loop with firestore

Unanswered
Cão Fila de São Miguel posted this in #help-forum
Open in Discord
Cão Fila de São MiguelOP
problem description:
I am implementing an online game that is like Jira with gamification methods, it works perfectly in single player mode, but in some cases in multiplayer the fire store get stuck between two states => the system falls in infinite loop transitioning between these two states.

Codes:
interface UpdateSessionParams { [key: string]: any; } export const updateSession = async ( gameDocumentID: string, sessionDocumentID: string, updateParams: UpdateSessionParams): Promise<void> => { try { const sessionDocRef = doc(db, "gamesData", gameDocumentID, "sessions", sessionDocumentID); await updateDoc(sessionDocRef, updateParams); console.log('Session updated successfully.'); } catch (error) { console.error('Error updating session:', error); } };
and this is the following chunk of code is where problem arise in multiplayer games
useEffect(() => { const updateMovesField = async () => { try { const updatedHexaItems = removeDuplicates(hexagonItems); const updateParams: { moves: any } = { moves: updatedHexaItems, }; if (sessionId) { await updateSession(sessionData.gameId, sessionId, updateParams); } } catch (error) { console.error('Error updating moves field:', error); } finally { setIsCardRemoved(false); } }; if (Object.keys(hexagonItems).length > 0 || isCardRemmoved) { updateMovesField(); setIsCardRemoved(false); } }, [hexagonItems, sessionId]); useEffect(() => { if (sessionData?.moves && sessionData.moves !== hexagonItems) { const updatedHexaItems = removeDuplicates(sessionData.moves); if ( JSON.stringify(previousMovesRef.current) !== JSON.stringify(updatedHexaItems) ) { setHexagonItems(updatedHexaItems); previousMovesRef.current = updatedHexaItems; } } }, [sessionData]);

1 Reply

Cão Fila de São MiguelOP
Tried these fixes:
1- I tried to implement a debouncing mechanism but it didn't solve the issue and had some duplication.
2- Tried to use fire store transaction, but it gets in infante loop when the component loads