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

215
Vistas
Using state with array,map / How to pass variable
function Header() {
    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());  
         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${key1}`)} className='modal_img'/>
   </div>
 );
}

export default Header;

'result' is a map, and I am trying to use keys in result.

( Because the keys of result(map) is image number that I am trying to use in img src path. --> ex ) img/img13.jpg )

I know that I have to use state, in order to pass variables. But don't know how to use.

(With code above I am getting this error--> 'key' is not defined no-undef)

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

0

Use this code:

import { useState } from "react";

function Header() {
    const [result , setResult] = useState({})
    const first = (e) => {
       
       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++){
           setResult({...result, [content.data[i].image_id] :content.data[i].caption})
        }

         var key = Array.from(result.keys());  
         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${key1}`)} className='modal_img'/>
   </div>
 );
}

export default Header;

You should also read the docs useState Hook

about 4 years ago · Juan Pablo Isaza Denunciar

0

function Header() {
    const [keys, setKeys] = useState([]); // defining a state using hook
    
    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);   // setting the state 
       var value = Array.from(result.values());
   });
}

so, you can use the state keys to access the name of the image wherever you want

you can find more about state hook here

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