i don't know why, after i call the fetch function in the useEffect, the getUsers function doesn't fill my data variable, i can't see rows of data in the MaterialTable, the structure of data is in columns, please help me i don't know how to do it and where i'm wrong.
function createData(name, surname, username, email) {
return { name: name, surname: surname, username: username, email: email };
}
export default function MaterialTab() {
const [state, setState] = useState({
columns: [
{ title: 'Name', field: 'name' },
{ title: 'Surname', field: 'surname' },
{ title: 'Username', field: 'username' },
{ title: 'Email', field: 'email' },
],
data: [],
});
useEffect(() => {
function getUsers(_callback) {
fetch('conn', {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
username: localStorage.getItem("username")
})
})
.then(response => response.json())
.then(responseJson => {
var name = new Array(responseJson[0]);
var surname = new Array(responseJson[1]);
var username = new Array(responseJson[2]);
var email = new Array(responseJson[3]);
var count = name[0]["length"];
var rows = new Array();
var i = 0;
while (i <= count) {
state.data.push(
createData(name[0][i], surname[0][i], username[0][i], email[0][i])
);
i++;
}
setState(state.data);
_callback();
})
.catch(error => {
console.error(error.toString());
});
};
getUsers(function() {
console.log("finish");
});
}, []);
return (
<MaterialTable
title="Clienti palestra"
columns={state.columns}
data={state.data}
/>
);
}
You have an issue on setting state using useState. I have updated your example. Please check it.
import MaterialTable from "material-table";
import React, {useEffect, useState} from "react";
function createData(id, name, username, email) {
return {id: id, name: name, username: username, email: email};
}
export default function MaterialTab() {
const columns = [
{title: 'Id', field: 'id'},
{title: 'Name', field: 'name'},
{title: 'Username', field: 'username'},
{title: 'Email', field: 'email'},
];
const [data, setData] = useState([]);
const submission = {
title: 'This is title',
body: 'This is body',
userId: 1
};
useEffect(() => {
function getUsers(_callback) {
fetch(`https://jsonplaceholder.typicode.com/users`, {
method: "GET"
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson, 'responseJson');
const results = [];
responseJson.map(res => {
results.push(
createData(res.id, res.name, res.username, res.email)
);
});
setData(results);
_callback();
})
.catch(error => {
console.error(error.toString());
});
}
getUsers(function () {
console.log("finish");
});
}, []);
return (
<div>
{
data ?
<MaterialTable
title="Clienti palestra"
columns={columns}
data={data}
/> : null
}
</div>
);
}