1

I am trying to make an app that displays all my users but I have trouble filling my table with my data.

I am using react-google-chart.

My table stays empty even when my data is not it just displays the information but is filled.

My code

import React from "react";
import { Chart } from "react-google-charts";

export const options = {
    title: "Users List",
    width: "100%",
};

const addData = (data) => {
    let dataToPush = []
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(dataToPush)
    };
    fetch('http://localhost:8000/users', requestOptions)
        .then(response => response.json())
        .then(dataToPush => {
            dataToPush.forEach((user) => {
                data.push([user.email, user.password, user.id])
            })
        });
}

export function Users() {
    let data = [["email", "password", "id"]];
    return (
        addData(data),
        <div className="center">
        <Chart
            chartType="Table"
            width="100%"
            height="400px"
            data={data}
            options={options}
        />
        </div>
    );
}
export default Users

I tried having data empty at the beginning. I Checked what my API is sending me:

[
    {
        "_id": "64931d7fc2cb9190fb20d0e1",
        "email": "name.email@gmail.com",
        "password": "$2b$10$ej0A4mWPZUzD0uHkX.1Lsuh4fsp1fn/bQDm4i5Jl6ui1o3ghQKUfW",
        "__v": 0
    },
    {
        "_id": "64932240c2cb9190fb20d0e9",
        "email": "name@gmail.com",
        "password": "$2b$10$LojaGJswWGznNY/xC/SwJe4ToytxRaWZPUNX8LbrcOeZxHbVpLMTy",
        "__v": 0
    }
]`

And when displaying my data on the console it is filled

1 Answers1

0

I've adapted your code to fix some issues, following the sandbox link:

The jsonplaceholder was used to simulate some real request

Sandbox

Output:

enter image description here

Code:

import React, { useEffect, useState } from "react";
import { Chart } from "react-google-charts";

const fetchuserData = async () => {
  const requestOptions = {
    method: "GET",
    headers: { "Content-Type": "application/json" }
  };
  const userData = await fetch(
    "https://jsonplaceholder.typicode.com/users",
    requestOptions
  );
  return await userData.json();
};

export const options = {
  title: "User List"
  //width: "100%"
};

export function App() {
  const [data, setData] = useState([["id", "name", "email"]]);

  const loadUsers = async () => {
    const users = await fetchuserData();
    setData((prevState) => {
      const usersTableFormat = users.map((user) => [
        user.id,
        user.name,
        user.email
      ]);

      return [...prevState, ...usersTableFormat];
    });
  };

  useEffect(() => {
    loadUsers();
  }, []);
  return (
    <>
      <Chart
        chartType="Table"
        width="100%"
        height="400px"
        data={data}
        options={options}
      />
    </>
  );
}

Issues:

  • Use state to reactive components.
  • In general, React recommends using the useEffect if you need to trigger some function when the component is created (there are other ways but start with it).

See the React docs: https://legacy.reactjs.org/docs/hooks-effect.html

  • Maybe it is a problem from my side but when I use your code and using my API call I keep having this **Failed to fetch** run time error. even tho my API is working fine when I use it using Postman. – Pierre Bourgery Jul 12 '23 at 12:14
  • be aware that I've changes to GET, in your code you are using POST: const requestOptions = { method: "GET", ... – Fabio Ribeiro de Carvalho Jul 12 '23 at 12:38
  • Also, send the message error – Fabio Ribeiro de Carvalho Jul 12 '23 at 12:39
  • Yes ! I changed It like it was, using GET, the problem stay the same maybe it comes from how i send my data because i send it using res.statues(200).json(users) – Pierre Bourgery Jul 12 '23 at 12:41
  • the error is as follow:Uncaught runtime errors: ERROR Failed to fetch TypeError: Failed to fetch at fetchuserData (http://localhost:3000/main.5a5b8050045717f39a0f.hot-update.js:35:26) at loadUsers (http://localhost:3000/main.5a5b8050045717f39a0f.hot-update.js:48:25) at http://localhost:3000/main.5a5b8050045717f39a0f.hot-update.js:55:5 at commitHookEffectListMount (http://localhost:3000/static/js/bundle.js:32616:30) at commitPassiveMountOnFiber (http://localhost:3000/static/js/bundle.js:34109:17) at commitPassiveMountEffects_complete – Pierre Bourgery Jul 12 '23 at 12:42
  • check if the backend is receiving the request with some console.log. Do u have the repo to this app (backend) – Fabio Ribeiro de Carvalho Jul 12 '23 at 12:49
  • My back does send send the request because it display my message using console.log ```exports.display = (req, res, next) => { User.find() .then(users => { console.log(users); res.status(200).json(users); }) .catch(error => { res.status(400).json({ error }); }) };``` – Pierre Bourgery Jul 12 '23 at 12:59
  • so check the network tab from your browser. It's not possible this not working if you're receiving the backend info. – Fabio Ribeiro de Carvalho Jul 12 '23 at 13:06
  • 1
    Thank you for your help I found kind of a solution When instead of using https I used http found th solution here https://stackoverflow.com/a/58003959/22204761 But now I have my informations in double – Pierre Bourgery Jul 12 '23 at 13:12
  • could be something with the develop mode that will run the useEffect two times. So, to try solve it see the update in the sandbox that I did in setData: https://codesandbox.io/s/google-chart-react-p2h2ky?file=/App.tsx – Fabio Ribeiro de Carvalho Jul 12 '23 at 14:29