Search code examples
reactjsfetch-api

filtering data after fetch for graph


I am fetching data from the database using API and the data will be used to show in the graph. below is the format of the API. I would like my graph to show just the time alone and not the date with the timezone. And is there a way to change the value from string to int?

API data
[{"time":"2022-01-13T15:26:20.129055+08:00","location":"north","value":"30","sensorType":null,"type":"temperature"},
{"time":"2022-01-13T15:54:31.718588+08:00","location":"north","value":"35","sensorType":null,"type":"temperature"}]
code for fetch and x,y for plotting graph
 const [data, setData] = useState([]);

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

  const asyncFetch = () => {
      fetch('api')
      .then((response) => response.json())
      .then((json) => setData(json))
      .catch((error) => {
        console.log('fetch data failed', error);
      });
  };
    const config = {
        data,
        xField: 'time',
        yField: 'value',


Solution

  • You can create a Date object from the time string and get the time as you need.

    Try like below.

    const apiData = {"time":"2022-01-13T15:26:20.129055+08:00","location":"north","value":"30","sensorType":null,"type":"temperature"};
    
    const timeStamp = new Date(apiData.time);
     
    // int value of time in millis
    console.log(timeStamp.getTime());
    
    // formatted time
    console.log(`${timeStamp.getHours()}:${timeStamp.getMinutes()}`);
    In your then block update the data before setting it to data.

    .then((json) =>
        setData(
            (json || []).map((item) => {
                const timeStamp = new Date(item.time);
                return {
                    ...item,
                    time: `${timeStamp.getHours()}:${timeStamp.getMinutes()}`,
                };
            })
        )
    )