简体   繁体   中英

How to display fetched data from API in react-table?

I have this sample data fetched from an API which updates periodically.

[
    {
        "name": "s1",
        "data": [
            {
                "time": "03:15:00",
                "score": "23" 
            },
            {
                "time": "03:14:00",
                "score": "43" 
            },
            {
                "time": "03:13:00",
                "score": "12" 
            },

        ]
    },
    {
        "name": "s2",
        "data": [
            {
                "time": "03:14:00",
                "score": "54" 
            },
            {
                "time": "03:13:00",
                "score": "34" 
            },
            {
                "time": "03:10:00",
                "score": "23" 
            },

        ]
    },
    {
        "name": "s3",
        "data": []
    },
    {
        "name": "s4",
        "data": [
            {
                "time": "03:16:00",
                "score": "ERR" 
            },
            {
                "time": "03:10:00",
                "score": "65" 
            },
            {
                "time": "03:09:00",
                "score": "54" 
            },

        ]
    }
]

This data updates every minute using this code:

const [data, setData] = useState([])

const getData = async () => {
    try {
        const myData = await axios.get('http://127.0.0.1:8000/my-drf-api')
        console.log("myData: ", myData.data);
        setData(myData.data);
    } catch (err) {
        console.error(err.message);
    }
};

useEffect(() => {

    getData()
    const interval = setInterval (() => {
        getData()
    }, 60000)

    return () => {
        clearInterval(interval)
    }
}, [])

Now I need to display it in a tabular format such that the first column shows the aggregated time for each name (s1-s4) sorted from latest to earliest, and the rest of the column showing the scores with the header of each columns as the names. Thus, the table gets updated every minute inserting new data in the top-most row.

It should be displayed like this:

在此处输入图像描述

I've looked into several React table libraries and the one that caught my attention is the react-table. However, I don't know how to set the time column, as well as the scores as accessors of the rest of the columns. Any help would be much appreciated.

You can use material UI table for display data into table, apply map on data and split data into respective rows and columns according to your requirements

for reference refer this link https://mui.com/components/tables/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM