Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cant replace value with useState in React

I try to replace the value of a variable when I click on a key but it doesnt work.
↓ this dont work but I want it to work

import React, { useState, useEffect } from 'react';

const List = ({ items }) => {

  const [myHTML, setMyHTML] = useState([]);

  function handleKeyPress(e) {
    if (e.key === "e" && window.location.pathname === '/PlayMode') {
      console.log('e pressed');
      setMyHTML([<div><h1>lol</h1></div>]);
    }
  }
  
  if (!document.eventListenerAdded) {
    document.addEventListener("keyup", handleKeyPress);
    document.eventListenerAdded = true;
  }

  return (
    <div>
      {myHTML}
    </div>
  );
};

If I put it in a timeout it work so I dont understand why.
↓ this work but i dont want it like that

import React, { useState, useEffect } from 'react';

const List = ({ items }) => {

  const [myHTML, setMyHTML] = useState([]);

  console.log('starting');
  let myTimeout = setTimeout(() => {
    setMyHTML([<div><h1>pok</h1></div>]);
  }, 2000);
  
  return (
    <div>
      {myHTML}
    </div>
  );
  
};

And I wont put it in a timeout with a 0 delay because I think there is an alternative right ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use useEffect to let it work.

    useEffect(() => {
        setMyHTML([
            <div>
                <h1>lol</h1>
            </div>,
        ])
    }, [])

Full code would be:

const List = ({ items }) => {
    const [myHTML, setMyHTML] = useState([])

    function handleKeyPress(e) {
        if (e.key === 'e' && window.location.pathname === '/PlayMode') {
            console.log('e pressed')
            setMyHTML([
                <div>
                    <h1>lol</h1>
                </div>,
            ])
        }
    }
    useEffect(() => {
        setMyHTML([
            <div>
                <h1>lol</h1>
            </div>,
        ])
    }, [])

    return <div>{myHTML}</div>
}

And you can put your determine statements(if else) in it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading