Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda