Ad

How To Fetch Json With React-Table Library

- 1 answer

the example to which I refer is the following: https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sub-components

I would like to fetch a json file and pass the elements of the latter into the table instead of generating them as in the previous example. The instructions for making fetch are clear to me but I can't understand how to integrate them in the "makeData" file.

This is my "makeData" code:

import ReactDOM from 'react-dom';

const range = len => {
  const arr = []
  for (let i = 0; i < len; i++) {
    arr.push(i)
  }
  return arr
}

const newPerson = () => {
  fetch('http://localhost:5000/api/azienda')
  .then(res => res.json())


 //   .then((rows) => {
  //     ReactDOM.render(this.makeData(rows), document.getElementById('root'));
   //   });
}

export default function makeData(...lens) {
  const makeDataLevel = (depth = 0) => {
    const len = lens[depth]
    return range(len).map(d => {
      return {
        ...newPerson(),
        subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
      }
    })
  }

  return makeDataLevel()
}

For any advice I will thank you

Ad

Answer

Create an array in the constructor ,where the data will be stored , fetch the data from the serverlink and then put it in the table

  constructor(props, context) {
    super(props, context);
    this.state = { items: []};
  }


  getList = () => {
    fetch("http://localhost:5000/api/azienda")
      .then(res => res.json())
      .then(items => this.setState({ items }))
      .catch(err => console.log(err));

  };

  componentDidMount() {
      this.getList();
  }
Ad
source: stackoverflow.com
Ad