Home > Blockchain >  Objects are not valid as a react component. (found: object with keys {}). If you meant to render a c
Objects are not valid as a react component. (found: object with keys {}). If you meant to render a c

Time:10-27

There are multiple questions with the same title but for some reason my case is simple but yet I'm unable to fix it.

I've an API which provides this response:

{
   "customer":{
      "default_address":{
         "address1":null,
         "city":null,
         "country":null,
         "first_name":"Chaudhry",
         "user_id":1234,
         "last_name":"Talha",
         "name":"Chaudhry Talha",
         "phone":"12345667",
         "province":null,
         "zip":"12345"
      }
   }
}

Which I'm storing in a state:

...
    const [customerInfo, setCustomerInfo] = useState({});
...
    setCustomerInfo(response.customer.default_address)
...

I get this error:

Objects are not valid as a react component. (found: object with keys {}). If you meant to render a collection of children, use an array instead.

Based on a solution I changed useState to:

const [customerInfo, setCustomerInfo] = useState([]);

Error: Objects are not valid as a React child (found: object with keys {user_id, first_name, last_name, address1, city, province, country, zip, phone, name, country, default}). If you meant to render a collection of children, use an array instead.

and it also gives me this error:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

For the above error, I'm basically doing this in my code:

    useEffect(() => {
          myservice.getUserProfile("USER_ID").then((response) => {
          setCustomerInfo(response.customer.default_address)
...
}, [])

I've also tried putting it as null:

const [customerInfo, setCustomerInfo] = useState(null);

but got the same error i.e. Objects are not valid as a React child (found: object with keys...

So, how do I parse it?

CodePudding user response:

I have just try your code in my local space ,

I can't really see a problem in your code i only change the type of your declaration in the state to null so they can take any type of data you are giving to them so try this :

  const [customerInfo, setCustomerInfo] = useState(null);
  const [shippingAddress, setShippingAddress] = useState(null);

CodePudding user response:

I assume you are trying to then map "shippingAddress"?

keep

const [customerInfo, setCustomerInfo] = useState([]);

and then

{shippingAddress.map((value, index) => {
    return(
    <p key={index}>{value.name}</p> //use this to adjust what you want to display
    )

})
  • Related