Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!