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
I've adapted your code to fix some issues, following the sandbox link:
The jsonplaceholder was used to simulate some real request
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}
/>
</>
);
}
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