简体   繁体   中英

How to fix error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

I'm trying to set the a state with an array of objects but I'm getting the above error and I do not know how to resolve it.

My code:

const [itemsInCart, setItemsInCart] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      await fetch("https://fakestoreapi.com/products?limit=16")
        .then((res) => res.json())
        .then((data) => {
          const initialItemCount = data.map((item) => {
            return {
              name: item.title,
              qty: 0,
            };
          });
          setItemsInCart(initialItemCount);
        });
    };

    fetchData();
  }, []);

I tried console.log(Array.isArray(initialItemCount)) to check if it is an array and it returned true. So why is it saying to use an array? Thank you

You can use a breakpoint to see the final value of itemsInCart , to check if this array contains the list of React child component.

From your code, I guess the array only contains the object of {name and qty}, which can not be rendered directly.

You may try parsing these objects to a component to render UI.

Hope this help.

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.

Related Question Objects are not valid as a React child. If you meant to render a collection of children, use an array instead - Error Solidity - React “Objects are not valid as a React child. If you meant to render a collection of children, use an array instead.” error Error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead ReactJS Error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Uncaught Invariant Violation: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Objects are not valid as a React child. If you meant to render a collection of children, use an array instead - FlatList Error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead. Getting data from JSON Cannot display data in ReactJS. Error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead React Error: Objects are not valid as a React child,If you meant to render a collection of children, use an array instead
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM