Search code examples
javascriptreactjsaxiosmaterial-table

How to use axios and get JSON data


I have problems about axios. I try to use material-table library and make table now. I wanna get Json data from "CheckListService" and set variable into "dataAll" but it doesn't work. I set variable Console said

Line 10:11: 'data' is assigned a value but never used no-unused-vars

Maybe it's easy error but I didn't understand. Please tell me why it doesn't work.

CheckList.js

import axios from 'axios'

const CHECKLIST_REST_API_URL = 'http://localhost:8080/api/list';

class CheckListService {

    getList() {
        return axios.get(CHECKLIST_REST_API_URL);
    }
}


export default new CheckListService();

Table.js

import React from 'react';
import MaterialTable from 'material-table';
import CheckListService from '../services/CheckList';

export const Table = () => {

    let dataAll = [];


    const data = () => {
        CheckListService.getList().then((response) =>
            dataAll = response.data
        )
    }



    const columns = [
        {
            title: 'リスト番号', field: 'listNo'
        },
        {
            title: '採用日', field: 'saiyouDate'
        },
        {
            title: 'バージョン', field: 'version'
        },
        {
            title: '種別', field: 'shubetu'
        },
        {
            title: 'ライセンス', field: 'licenseManage'
        },
        {
            title: '用途', field: 'youto'
        },
        {
            title: '備考', field: 'bikou'
        },
        {
            title: '承認者', field: 'authorizer'
        },
        {
            title: '承認日', field: 'approvalDate'
        },
        {
            title: 'URL', field: 'url'
        }
    ]


    return (
        <div>

            <MaterialTable title="MaterialTable"

                data={dataAll}
                columns={columns}


            />
        </div>
    )


}

Solution

  • A couple of things -

    • use state in order to get the component to rerender once you have the received the data from the API
    • use an effect for running async requests, at the minute you are almost running the request on ever rerender, which is bad.
    const [dataAll, setDataAll] = useState([]);
    
    useEffect(() => {
       CheckListService.getList().then((response) =>
          setDataAll(response.data)
       )
    }, []) // <!-- empty array has this effect run once, on mount.