I'm a newbie in react and I'm trying to make a GET request to my own API and then render the result on the screen. When I do that, I console.log
my result as well and in the console I get it right, but I can't put it on my screen. I was using useState
for this.
My code:
const url = "http://localhost:2000/appShop";
const [shop, showShop] = useState("");
const getShop = () => {
Axios.get(url).then((response) => {
console.log(response);
showShop(response.data.name response.data.address response.data.city);
});
};
<Box
sx={{
"& > :not(style)": { m: 1, width: "25ch" },
}}
>
<span>{shop}</span>
<Button onClick={getShop}>List all Shops</Button>
<Button onClick={() => showShopCard(false)}>Close</Button>
</Box>
I get it in console, but not on my screen
CodePudding user response:
Your response.data is an array. You need to loop through the array and save the result in a state, moreover you need to create a span item for each element in the array:
const url = "http://localhost:2000/appShop";
const [shop, showShop] = useState("");
const [shopList, setShopList] = useState([]);
const getShop = () => {
Axios.get(url).then((response) => {
console.log(response);
const shopListItems = [];
response.data.forEach(resItem => {
shopListItems.push(resItem.name resItem.address resItem.city)
})
setShopList(shopListItems)
});
};
<Box
sx={{
"& > :not(style)": { m: 1, width: "25ch" },
}}
>
{shopList.map((sl, index) => (<span key={index}>{sl}</span>))}
<Button onClick={getShop}>List all Shops</Button>
<Button onClick={() => showShopCard(false)}>Close</Button>
</Box>