0

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:


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.

0

1 Answer 1

1
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 ];
Sign up to request clarification or add additional context in comments.

1 Comment

It worked, thank you. I need practice!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.