My problem is, that I want to show word by word on the website, iterating through a text. I am using state variables to append the words, set by useEffect.
What I did is, that I call useEffect() , write first word in a state variable and by doing this trigger useEFfect again to write the next word into state variable. In the render section I just show the state variable and it should show the whole text word by word. I initially added also an interval to set speed, but just commented it out to test. In the console.log I can see the index increasing correctly and words are read correctly from words array, but the second word is missing in the state variable (btw. I also tried that with the letters and it was also second index not shown in state variable and additionally sometimes even more letters messed up). Generally it seems to be some kind of timing issue, but I do not really understand, why it is not working, no matter what interval is set...hope someone can help.
This is my code:
let index = useRef(0);
const words = text.split(" ");
useEffect(() => {
const tick = () => {
console.log("Index: ", index.current);
console.log("Length: ", words.length);
console.log("Char: ", words[index.current]);
console.log("placeholder: ", placeholder);
setPlaceholder((prev) => prev + " " + words[index.current]);
index.current++;
};
if (index.current < words.length - 1) {
/* let addChar = setInterval(tick, 70);
return () => clearInterval(addChar); */
tick();
}
}, [placeholder]);
---some other stuff----
return
<div>{placeholder}</div>