Sylv Ain
Sylv Ain

Reputation: 151

Impossible to get the value of an Usestate in a function

I want to have a blink cursor in a ...

I wrote this code, but impossible for me to understand why it's not working.

const [cursor,setCursor]=useState<string>("");

function blink(){

    if(cursor == '|'){
        setCursor("")
    }
    else{
        setCursor("|")
    }
    setTimeout(function(){ blink()}, 1000);
}


useEffect(() => {
    blink();
   }, []);


    return (
        <div>
            <span>{text}</span><span>{cursor}</span>
        </div>
    );
};

Thanks in advance :)

Upvotes: 0

Views: 65

Answers (2)

hackape
hackape

Reputation: 19947


function blink(){
    if(cursor == '|'){
        setCursor("")
    }
    else{
        setCursor("|")
    }
}

useEffect(() => {
    setTimeout(blink, 1000); // <- move setTimeout to here
}, [cursor]);  // <- and you need to pass cursor as a dep

Upvotes: 1

Patrick Roberts
Patrick Roberts

Reputation: 51756

Seems like you wanted this:

const [cursor, setCursor] = useState('');

useEffect(() => {
  const handle = setInterval(() => {
    setCursor(oldCursor => oldCursor === '|' ? '' : '|');
  }, 1000);

  return () => {
    clearInterval(handle);
  };
}, [setCursor]);

return (
  <div>
    <span>{text}</span><span>{cursor}</span>
  </div>
);

Upvotes: 1

Related Questions