reactjsarraysobjectreact-context

React useContext(): Objects are not valid as a React child when trying to execute function in useContext() api to fetch data


I want to fetch the data by running the API in the useContext() api, basically this API gives me the number of items added in the cart and I need that number only which Im using it in Cart.js component.

Now I want to run this context when I add item in ProductDetails.js component and when I delete item in Cart.js obviously without reloading the app.

Here is my useCartItems() custom hook:-

import { useEffect, useState } from "react";
import { getCartDetail } from "../components/services/_getMethod";

export default function useCartItems() {
    const dealer_id = sessionStorage.getItem("dealer_id");
    const [items, setItems] = useState([]);

    const fetchCartItems = () => {
        // getCartDetail() is common api function
        getCartDetail("api/ProductDetails/GetCountProductList", dealer_id).then(
            (data) => {
                setItems(data.data.length);
            }
        );
    }

    useEffect(() => {
        fetchCartItems();
    }, [])

    return { items, fetchCartItems };
}

Here is my CartContext.js:-

import { createContext, useEffect, useState } from "react";
import useCartItems from "../custom-hook/useCartItems";

export const CartItemContext = createContext();

export const CartItemProvider = ({ children }) => {

    const { items, fetchCartItems } = useCartItems();

    return <CartItemContext.Provider value={{ items, fetchCartItems }}>
        {children}
    </CartItemContext.Provider>
}

This is my Cart.js where in deleteCartItem() function I'm executing my custom hook fetchCartItems() :-

export default function Cart(){
    const { fetchCartItems } = useContext(CartItemContext);

    const deleteCartItem = async (itemId) => {
    try {
      // common delete function
      deleteCart("api/ProductDetails/delete_cart", itemId).then((data) => {
        fetchCartItems();
      });
    } catch (err) {
      console.error(err);
    }
  };


    //Rest JSX
   return <button onClick={() => deleteCartItem(itemId)}>remove</button>
}

👆This code same goes in ProductDetails.js component to add items in the cart.


Hence with all these it seems to me that it should be working but instead Im getting this error when the page loads:-

Unexpected Application Error! Objects are not valid as a React child. If you meant to render a collection of children, use an array instead.


Solution

  • import { useEffect, useState } from "react";
    import { getCartDetail } from "../components/services/_getMethod";
    
    export default function useCartItems() {
        const dealer_id = sessionStorage.getItem("dealer_id");
        const [items, setItems] = useState([]);
    
        const fetchCartItems = () => {
            // getCartDetail() is common api function
            getCartDetail("api/ProductDetails/GetCountProductList", dealer_id).then(
                (data) => {
                   // it stores length setItems(data.data.length);
                    setItems(data.data);
                }
            );
        }
    
        useEffect(() => {
            fetchCartItems();
        }, [])
    
        return { items, fetchCartItems };
    }
    

    why are u storing length in the items? the setItems stores an number to the items state variable and I think somewhere u tried to map this or take this value expecting it to be as array.