$currentWord.on(startGame, (_, word) => word);
import {useEffect} from 'react';
import WordDisplay from "@/shared/ui/word-display/index.jsx";
import {useUnit} from "effector-react";
import {$currentWord} from "@/features/game/model/store.js";
import {startGame} from "@/features/game/model/events.js";
It looks like there are a few issues in your Effector and React setup that are causing errors, primarily related to event loops and store updates. Below, I’ll outline the problems and provide corrected code for each part of your implementation.
1. Effect (effects.js)
Issue:
Infinite Loop: The line fetchWordFx.doneData.watch(word => startGame()); creates an infinite loop. Here's why:
startGame triggers fetchWordFx.
Once fetchWordFx completes, it triggers startGame again via the watcher.
This cycle repeats indefinitely.
Solution:
Remove the Watcher: Eliminate the watcher that causes the infinite loop.
Handle Store Updates Correctly: Ensure that the store listens to the effect's doneData to update the state.
Corrected effects.js:
javascript
// effects.js
import { createEffect } from "effector";
import { PATH_JSON_WORDS } from "@/shared/constants/index.js";
export const fetchWordFx = createEffect(async () => {
try {
const response = await fetch(PATH_JSON_WORDS);
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.statusText}`);
}
const words = await response.json();
if (!Array.isArray(words) || words.length === 0) {
throw new Error("Words data is invalid or empty.");
}
const idx = Math.floor(Math.random() * words.length);
console.log("Fetched Word:", words[idx]);
return words[idx].en;
} catch (error) {
console.error("Failed to fetch word:", error);
throw error;
}
});
2. Events (events.js)
Issue:
No immediate issues, but ensure that the startGame event doesn't unintentionally carry payloads that could interfere with the flow.
Solution:
Keep It Clean: Ensure startGame is used solely to trigger the effect without expecting any payload.
Incorrect Event Listener:$currentWord is listening to the startGame event instead of the fetchWordFx.doneData event. Since startGame doesn't carry the fetched word as payload, the store doesn't update correctly.
Solution:
Listen to the Correct Effect: Update $currentWord to listen to fetchWordFx.doneData, which carries the fetched word.
Corrected store.js:
javascript
// store.js
import { createStore } from "effector";
import { fetchWordFx } from "@/features/game/model/effects.js";
export const $currentWord = createStore('');
export const $guessesTotal = createStore(0);
export const $attemptsTotal = createStore(0);
// Update $currentWord when fetchWordFx successfully fetches data
$currentWord.on(fetchWordFx.doneData, (_, word) => word);
// Optionally, handle errors or loading states
// Example for logging errors (can be expanded as needed)
fetchWordFx.failData.watch(error => {
console.error("Error fetching word:", error);
});
4. Triggering the Effect (events.js continued)
Issue:
Ensure that when startGame is triggered, it correctly invokes fetchWordFx.
Solution:
Link startGame to fetchWordFx: Use .watch to call the effect when startGame is triggered.
Corrected events.js (continued):
javascript
// events.js (continued)
import { fetchWordFx } from "@/features/game/model/effects.js";
// When startGame is triggered, run fetchWordFx
startGame.watch(() => {
fetchWordFx();
});
5. React Component (GamePage.jsx)
Issue:
The component is generally set up correctly, but ensure that it responds to store updates and handles errors or loading states if necessary.
Solution:
Maintain Simplicity: Trigger startGame on mount and display the current word.
Optional Enhancements: Handle loading and error states for better UX.
Infinite Loop Creation: Caused by having fetchWordFx.doneData trigger startGame again.
Incorrect Store Listener:$currentWord was listening to startGame instead of the effect's completion.
By removing the unintended watcher and correctly linking the store to listen to the effect's successful completion, the application should function as expected without errors.
If you implement these corrections and enhancements, your game should start correctly, fetch a word, and display it without any infinite loops or state inconsistencies.