Encountering the error message "BarChart in react.js is not iterable"

I encountered an issue with the BarChart component:

An error message saying "undefined is not iterable!" appeared.

The API response I received looks like this:

{
  "saleCharts": [
    {
      "priceSum": 0,
      "categoryName": "string"
    }
  ],
  "statusCharts": [
    {
      "qtySum": 0,
      "status": "string"
    }
  ]
}

In my React code, I have implemented the following logic:

function Dashboard({ notifyData }) {

    const [orderData, setOrderData] = useState([]);
    const [dashboardData, setDashboardData] = useState([]);
    const [newOrderCount, setNewOrderCount] = useState(0);

    useEffect(() => {

        getNewOrder();
    }, [notifyData]);

    var getNewOrder = function () {
        let orderResp = [];
        axios.get(GetNewOrdersUrl + '/2').then(response => {
            orderResp = response.data;
        })
            .then(() =>
                axios.get(OrderDashboardUrl).then(response => {
                    setOrderData(orderResp.orderList);
                    setNewOrderCount(orderResp.count);
                    setDashboardData(response.data.saleCharts);

                }))
    };
}
return (
    <>
        <BarChart
            xAxis={[
                {
                    id: 'barCategories',
                    data: dashboardData.map(item => item.categoryName),
                    scaleType: 'band',
                },
            ]}
            series={[
                {
                    data: dashboardData.map(item => item.priceSum),
                },
            ]}
            colors={['#d75b47']}
            width={1000}
            height={350}
        />
    </>
)

I would appreciate any insights on why this problem occurred and how to resolve it.
My understanding is that the BarChart component renders before the state is properly set.

Answer №1

The issue at hand pertains to the series prop within the BarChart component. This particular prop necessitates a description of the data required for rendering. The series prop should receive an array containing the necessary data objects, with none of these objects having undefined values. For more information, refer to the BarChart Documentation.

To address this issue, there are two potential solutions:

  1. Assign a default state to the dashboardData state:
const [dashboardData, setDashboardData] = useState([ { priceSum: 0 } ]);
  1. Display the BarChart component only when the dashboardData state contains values. As a result, it will not render during the initial render if the dashboardData is empty:
return (
   !!dashboardData.length && (
      <BarChart ... />
   )
);

You can access a DEMO LINK for easy testing and reviewing.

We hope that this explanation proves helpful and clear for those in need of assistance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Sinon to create a mock of a function

I'm having trouble figuring out a simple task like the one below: render() { return ( <div className="messageDetail"> <div className="messageForm" > Name: <input id="senderMsgName" value={this.props.nameVa ...

Using getStaticPaths and getStaticProps with moralis query for dynamic data fetching

I've been trying to getStaticPaths and getStaticProps to work, but I feel like I might be overlooking something. I attempted querying inside each of them, which seems redundant, but I'm not sure how else to do it. Can someone provide an example? ...

The value retrieved from redux appears to be varying within the component body compared to its representation in the return

Trying to fetch the most recent history value from the redux store to pass as a payload is presenting a challenge. When submitting a query, the history updates and displays the latest value within the map() function in return(), but when checking at // CON ...

How can I revert a date format using date-fns?

Greetings from Thailand! I have a question regarding the reverse formatting using date-fns. Is there a way to create a function that will change "saturday-9-september-2564" back to "2022-09-24" using date-fns? Any insights or methods on achieving this wo ...

React JS iterates through incorrect properties

Currently, I am retrieving two types of keywords from an API - user-added keywords and allowed keywords. Despite setting up the actions and reducers correctly, I am facing an issue where mapping through the 'keywords' props also includes the allo ...

Ways to encourage children to adopt a specific trait

Let's discuss a scenario where I have a React functional component like this: const Test = (props: { children: React.ReactElement<{ slot: "content" }> }) => { return <></> } When a child is passed without a sl ...

What's the deal with session-based middleware?

In the way my architecture is structured: I have Next.js (browser) connecting to Next.js (middleware), which then talks to a 3rd-party API. The middleware has the task of managing and storing users' access tokens. Currently, everything is functioni ...

Passing Object Data from Child to Parent Component in React and Leveraging its Functionality

After performing a date calculation, I stored the values of year, month, and day in an object. Now, my goal is to send this object to the parent component App.js, and then pass that data to another child component named Modal.js as a prop. I want to displa ...

Can you help me figure out why my Fetch request from the Nodejs backend isn't working?

I keep encountering an error every time I try to make a fetch request: server running on 8000 port { type: 'https://httpstatus.es/401', status: 401, title: 'Unauthorized', detail: 'Access token invalid or expired' } Ev ...

I keep encountering an error that says "ReferenceError: localStorage is not defined" even though I have already included the "use

I have a unique app/components/organisms/Cookies.tsx modal window component that I integrate into my app/page.tsx. Despite including the 'use client' directive at the beginning of the component, I consistently encounter this error: ReferenceErr ...

Exclude babel.config.js from being processed by Next.js

Currently, I am working on a Next.js application and I need to customize Babel in order to run my Jest test suite. The issue I'm facing is that when I configure the babel.config.js file, Jest runs successfully but Next.js also picks up this configurat ...

The functionality to save user likes in React is not properly functioning on the like button

I created a like button in React that saves my choices, but it seems to be not saving the choices of other users. Additionally, it doesn't appear to restrict only authenticated users from marking likes. Can someone please help me identify what I' ...

Use React Router to create a link that goes to the same URL but passes along unique state

Can someone help me figure out how to open the same URL using react-router Link while passing different state each time? <Link to={items.vehicleModelId === 2 ? '/ecgo-3' : items.vehicleModelId === 3 && '/ecgo-5' ...

Unreachable prevState when utilizing the useState hook

I am currently working on a component where I need to capture the previousState of an element. However, no matter what I try, it keeps returning the initial value. This suggests that there is some re-rendering happening, causing it to constantly default to ...

Managing authentication in React applications

As a FrontEnd developer, I have limited knowledge when it comes to security. Currently, I am saving the userId of users in web localStorage so that requests can be made to the server for user information. However, I am concerned about the potential risks i ...

The React Hook useEffect is missing a dependency: 'handleLogout'. Make sure to either add it to the dependency array or remove it from the useEffect hook

import { useState, useEffect } from "react"; import LoginModal from "./LoginModal"; import { NavLink, useLocation, useNavigate } from "react-router-dom"; import { useDispatch } from "react-redux"; import { userLogout ...

Javascript: What is the best way to narrow down search results using multiple values, regardless of the sequence in which they are entered?

React: How can I improve search result filtering to accommodate multiple values (irrespective of word order)? Example: I want to search for the title of a document using variations like "phone repair process," "repair phone process," or "process phone repa ...

React Native application for IOS crashes when navigation is implemented

Currently, I am utilizing react-native-reanimated:3.4.2 react-native:0.72.3 Upon using navigation.reset or navigation.replace in my iOS react native app, the application crashes without any indication. However, when running the app through Xcode, th ...

Customizing the default button in Ant Design Popconfirm to display "Cancel" instead

When the Ant Design Popconfirm modal is opened, the Confirm ("Yes") button is already preselected. https://i.stack.imgur.com/bs7W7.png The code for the modal is as follows: import { Popconfirm, message } from 'antd'; function confirm(e) { c ...

Troubleshooting the issue of having multiple menu items in Material UI

Every time I attempt to add the Menu component multiple times, I encounter an issue with the popup list displaying incorrectly. To demonstrate this problem, you can view it through the link provided on codesandbox below. I have included data-id attributes ...