Search code examples
javascriptjsonreactjses6-promisematerial-table

Fix Issue with React Material-table to Display Remote Data


I have a remote data which is sent as array object. I convert this to JSON array in order to show this data in Material data table. I am able to call the API and when I log the response I can see the converted JSON as the data below:

[{"xxxx":"xxxx","yyyy":5,"zzzz":3,"tttt":1,"qqqqq":"some-data"}]

Unfortunately I am unable to show this data in the table while also implementing paging as well. Please find my codes below and assist me to fix this issue:

data={query =>
          new Promise((resolve, reject) => {
            let formData = new FormData();
            const userid = 'someID'

            formData.append('userid', userid);
            const config = {
              headers: { 'content-type': 'multipart/form-data' },
            };

            let url = 'http://urlendpoint?'
            url += 'per_page=' + query.pageSize
            url += '&page=' + (query.page + 1)
            fetch(url, {
              method: 'POST',
              body: formData,
              config
            })
              .then(response => response.json())
              .catch((error) => {
                console.log(error.response);
              })
              .then(result => {
                let resultData = JSON.stringify(result);
                console.log('result: ' + resultData);
                resolve({
                  data: resultData,
                  page: resultData.page - 1,
                  totalCount: resultData.total,
                })
              })
          })
        }

Also, I am following this link to implement the material table: https://material-table.com/#/docs/features/remote-data


Solution

  • I actually removed the conversion to JSON string and everything works fine. See my updated codes below:

    data={query =>
      new Promise((resolve, reject) => {
        let formData = new FormData();
        const userid = 'someID'
    
        formData.append('userid', userid);
        const config = {
          headers: { 'content-type': 'multipart/form-data' },
        };
    
        let url = 'http://urlendpoint?'
        url += 'per_page=' + query.pageSize
        url += '&page=' + (query.page + 1)
        fetch(url, {
          method: 'POST',
          body: formData,
          config
        })
          .then(response => response.json())
          .catch((error) => {
            console.log(error.response);
          })
          .then(result => {
                resolve({
                  data: result,
                  page: result.page - 1,
                  totalCount: result.total,
                })
              })
      })
    }