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.
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`)}/>
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>
);
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