Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

build table with react table with api

good morning colleagues, I was building a table with data that is brought from after consuming the api, the problem is that this data does not have the normal structure of a json.

The file that the server gives me is this:

{
  "Sensor_Id": "1",
  "Temperature": "35.27",
  "Humidity": "61.4"
}

As you can see, it does not have the brackets ([]), that is why it does not read the variables when building the table, here I consume the api:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


export function Sensores(props) {
  const [sensores, setSensores] = useState([]);

  const fetchSensores = async () => {
    const response = await axios
      .get("https://my-json-server.typicode.com/ijrios/prueba2/sensores")
      .catch((err) => console.log(err));

    if (response) {
      const sensores = "["+response.data+"]";

      console.log("Sensores: ", sensores);
      setSensores(sensores);
    }

  };

and here I build the columns:


const columns = useMemo(
    () => [
      {
        Header: "Id",
        accessor: "Sensor_Id",
      },
      {
        Header: "Temperatura",
        accessor: "Temperature",
      },
      {
        Header: "Humedad",
        accessor: "Humidity",
      },
    ],
    []
  );

  const DatoSensores = useMemo(() => [...sensores], [sensores]);

  const tableInstance = useTable(
    {
      columns: columns,
      data: DatoSensores,
    }
  );

As the file that arrives is a json with a different structure, it does not write any data to the table, I need help to be able to read data and display it on the screen, thx u.

>Solution :

const sensores = "["+response.data+"]";

This generates a string with [ ‘s around response.data


React Tables needs a regular array as data source, so lets make one;

const sensores = [ response.data ];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading