I'm trying to set a state. Here is my code:
import React, { Component, useRef, Fragment, useEffect, useState } from "react";
import axios from "axios";
const Cart = (props) => {
const [useCart, setCart] = useState([]);
useEffect(() => {
(async () => {
const result = await axios
.get('https://example.com/sample')
.then((res) => {
setCart(res.data);
})
.catch((err) => {
console.error(err);
});
})();
}, []);
console.log(useCart);
return (
<div></div>
);
}
export default Cart;
The API returns value like that:
[
{
'id': 5,
'qwe': 'qwe',
'asd': [
{
'aaa': 'aaa',
'bbb': 'bbb'
}
],
'zxc': 'zxc'
},
{
'id': 7,
'qwe': 'qwe',
'asd': [
{
'aaa': 'aaa',
'bbb': 'bbb'
}
],
'zxc': 'zxc'
}
]
I'm not rendering this on component. I'm just trying to console log it. But it give error like that:
Error: Objects are not valid as a React child (found: object with keys {id, qwe, asd, zxc}). If you meant to render a collection of children, use an array instead.
I couldn't understand, where do I do wrong.
Don't know what's going wrong with your code but maybe I can help you debug it. I copied your API's response to a file and simply imported it inside the component to a variable. I then set the state to that variable and everything works fine, all console logs and everything. Check it out here-
https://codesandbox.io/s/angry-ramanujan-3k97v?file=/src/App.js
That tells me the problem could be coming from your useEffect
where you are handling your API response.
One change that I made and I think you should do it too when you logout a state variable you should do it inside a lifecycle hook. So you should put your console.log(useCart);
inside this useEffect(()=>{ console.log(useCart); },[useCart])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.