Search code examples
javascriptreactjsrecharts

Got error: `RangeError: invalid time value` while set XAxis date value use date-fns


I am using recharts to present a data array as an area chart. My code fetches mydata array from a remote API with the lines below:

const [myData, setMyData] = useState([]);
useEffect(() => {
const getData = async () => {
      const resp =  await fetch('https://api.contoso.xyz/api');
      const jsonResp = await resp.json();
      setMyData(jsonResp);
    };

    getData();
    }, []);

the data JSON array looks like this:

[
{"date": "2022-03-01",
"value": 123456,
},
{"date": "2022-03-02",
"value": 100000,
}
]

The React chart component looks like this:

...
import { format, parseISO } from date-fns
...
<ResponsiveContainer width="100%" height={400}>
  <AreaChart data={mydata} >
      <Area type="monotone" dataKey="value" stroke="#82CA9D" fill="#82CA9D" />
      <XAxis dataKey="date" tickFormatter={(str) => {
              const dateObj = parseISO(str);
              return format(dateObj, "MMM d");
            }}/>
     <YAxis />
     <Tooltip />
     <CartesianGrid opacity={0.5}/>
  </AreaChart>
</ResponsiveContainer>

When run the react site, I am getting the errors below

RangeError: Invalid time value
    at Em (main.5e916930.js:2:575929)
    at tickFormatter (main.5e916930.js:2:577712)
    at Function.value (main.5e916930.js:2:406091)
    at Function.value (main.5e916930.js:2:404369)
    at a.value (main.5e916930.js:2:402724)
    at a.value (main.5e916930.js:2:403854)
    at Eu (main.5e916930.js:2:143688)
    at Su (main.5e916930.js:2:143484)
    at pl (main.5e916930.js:2:178073)
    at lc (main.5e916930.js:2:163912)

The weird thing is if I change the XAxis section to something below, the local run will actually show the chart successfully.

<XAxis dataKey="date" tickFormatter={(str) => {
              const dateObj = parseISO(str);
              return format(dateObj, "MMM d");
              return str;
            }}/>

Now if I remove return str; from the above section of code, the chart will still work locally. When the chart didn't work, if I add console.log(str) in front of const dateObj = parseISO(str);, the output I get in console is showing auto instead of the actual date string.

Not sure what caused this kind behavior. Anyone know what is going on with my code?


Solution

  • Figured out what the problem is. The myData array is not yet populated when the page initially loaded (Because fetch is async?). That caused the str value to be auto or 0 (Don't know exactly why). This happens every time I re-started the test site locally. If I change the code while the local test site is already up, the chart loads successfully without issue as the array has already been populated.

    To get rid of this issue, I added a check condition before reformat the date string.

    if ( str === 'auto' || str === 0){
          return str;
    }else{
          console.log(str
          const dateObj = parseISO(str);
          return format(dateObj, "MMM d");
      }
    

    Not sure if this is the best way to solve this kind problem. Any better suggestions are welcome.