Reputation: 29
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)
Upvotes: 1
Views: 657
Reputation: 355
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
Upvotes: 1
Reputation: 562
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
Upvotes: 1