Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

240
Vistas
Using State Hook - (state variable) is not defined no-undef
function Header() {
    const [keys, setKeys] = useState([]); //added

    const first = (e) => {
       var result = new Map()
       axios.post('http://localhost:8000/' + query)
       .then(function(response){
         var content=JSON.parse(JSON.stringify(response)).data
         for (var i=0;i<content.data.length;i++){
           result.set(content.data[i].image_id, content.data[i].caption)
        }

         var key = Array.from(result.keys());  
         setKeys(key); //added
         var value = Array.from(result.values());   
       
      }).catch(err => {
         console.log("error");
         alert(err);
       });
     };

   const second = () => {}
    

 return (
   <div>
       <button onClick={(e)=> { first(); second(); }}/>
       <img src={require(`img/img${key[0]}.jpg`)}/>
   </div>
 );
}

export default Header;

I asked a question here Using state with array,map / How to pass variable and from the answers I got I edited the code like this. However I still get this error -->'key' is not defined no-undef

I thought maybe it has something to do with https://reactjs.org/docs/hooks-rules.html (Only Call Hooks at the Top Level). But I can't figure it out.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

The problem is typo.

You wrote keys instead of key.

your code should be like:

  const [keys, setKeys] = useState([])
  <img src={require(`img/img${keys[0]}.jpg`)}/>
about 4 years ago · Juan Pablo Isaza Denunciar

0

Your state variable is keys not key. If you access key you will get key is not defined.

return (
   <div>
       <button onClick={(e)=> { first(); second(); }}/>
       <img src={require(`img/img${keys[0]}.jpg`)}/>
   </div>
 );
about 4 years ago · Juan Pablo Isaza Denunciar

0

The problem has nothing to do with what you suspected

const [keys, setKeys] = useState([]); //added

<img src={require(`img/img${key[0]}.jpg`)}/>

You've defined the state to be keys, but in your img tag you are accesing key[0], hence it's saying key is undefined

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda