Hi,
I've been pulling my hair over the last few days trying to figure out how to make a POST request using hooks (basically adding new user data to my local database, then re-render with the data added)
My user data details looks are:
state = {
firstName: '',
lastName: '',
role: ''
}
I was able to get data from my database but I'm having a hard time with POST request. Can anybody help please?
import React, { useState, useEffect } from 'react';
import MaterialTable from 'material-table';
import columns from '../../backend/columns';
import axios from 'axios';
import { withRouter } from 'react-router-dom';
function UserTable(props) {
const [state, setState] = useState();
const apiURL = '/rest/users'
useEffect(() => {
const fetchData = async () => {
const result = await axios(apiURL);
setState(result.data);
console.log(result);
};
fetchData();
}, []);
return ( <MaterialTable
title = "Site Staff CV & GCP Log"
columns = {columns}
data = {state}
editable={{
onRowAdd: (newData) =>
new Promise(resolve => {
setTimeout(() => {
resolve();
const data = [...newData.data];
data.push(newData)
setState({ ...state, data });
}, 600);
}),
onRowUpdate: (newData, oldData) =>
new Promise(resolve => {
setTimeout(() => {
resolve();
const data = [...state.data];
data[data.indexOf(oldData)] = newData;
setState({ ...state, data });
}, 600);
}),
onRowDelete: oldData =>
new Promise(resolve => {
setTimeout(() => {
resolve();
const data = [...state.data];
data.splice(data.indexOf(oldData), 1);
setState({ ...state, data });
}, 600);
}),
}}
/>
);
}
export default withRouter(UserTable);
Hey below code will give you some basic ideas how it works in Material Table , there are some other ways to do as well.
```
import MaterialTable from "material-table";
import React, { useEffect, useState } from "react";
import axios from "axios";
export default function ReportTable() {
const [entries, setEntries] = useState({
data: [
{
id: "",
date: "",
description: "",
totalTime: ""
}
]
});
const [state] = React.useState({
columns: [
{ title: "Date", field: "date", type: "date" },
{ title: "Description", field: "description" },
{ title: "Total Hours", field: "totalTime" }
]
});
useEffect(() => {
axios
.get("http://localhost:8080/report")
.then(response => {
let data = [];
response.data.forEach(el => {
data.push({
id: el.id,
date: el.date,
description: el.description,
totalTime: el.totalTime
});
});
setEntries({ data: data });
})
.catch(function(error) {
console.log(error);
});
}, []);
return (
<MaterialTable
title="Report Table"
columns={state.columns}
data={entries.data}
editable={{
onRowUpdate: (newData, oldData) =>
new Promise(resolve => {
setTimeout(() => {
resolve();
const data = [...entries.data];
data[data.indexOf(oldData)] = newData;
axios
.put("http://localhost:8080/report", newData, {
params: {
id: entries.data[0].id
}
})
.then(res => console.log(res.data));
setEntries({ ...entries, data });
}, 600);
}),
onRowDelete: oldData =>
new Promise(resolve => {
setTimeout(() => {
resolve();
const data = [...entries.data];
data.splice(data.indexOf(oldData), 1);
axios
.delete("http://localhost:8080/report", {
params: {
id: entries.data[0].id
}
})
.then(res => console.log(res.data));
setEntries({ ...entries, data });
}, 600);
})
}}
/>
);
}
Hey below code will give you some basic ideas how it works in Material Table , there are some other ways to do as well.
import MaterialTable from "material-table"; import React, { useEffect, useState } from "react"; import axios from "axios"; export default function ReportTable() { const [entries, setEntries] = useState({ data: [ { id: "", date: "", description: "", totalTime: "" } ] }); const [state] = React.useState({ columns: [ { title: "Date", field: "date", type: "date" }, { title: "Description", field: "description" }, { title: "Total Hours", field: "totalTime" } ] }); useEffect(() => { axios .get("http://localhost:8080/report") .then(response => { let data = []; response.data.forEach(el => { data.push({ id: el.id, date: el.date, description: el.description, totalTime: el.totalTime }); }); setEntries({ data: data }); }) .catch(function(error) { console.log(error); }); }, []); return ( <MaterialTable title="Report Table" columns={state.columns} data={entries.data} editable={{ onRowUpdate: (newData, oldData) => new Promise(resolve => { setTimeout(() => { resolve(); const data = [...entries.data]; data[data.indexOf(oldData)] = newData; axios .put("http://localhost:8080/report", newData, { params: { id: entries.data[0].id } }) .then(res => console.log(res.data)); setEntries({ ...entries, data }); }, 600); }), onRowDelete: oldData => new Promise(resolve => { setTimeout(() => { resolve(); const data = [...entries.data]; data.splice(data.indexOf(oldData), 1); axios .delete("http://localhost:8080/report", { params: { id: entries.data[0].id } }) .then(res => console.log(res.data)); setEntries({ ...entries, data }); }, 600); }) }} /> ); }
Thanks fazaal, I did manage to solve it eventually but I'll try this.
Can you please share your code?
To get an idea of how it can be done, I am confused. @jakecinco
@p9614 the code fazaal showed above worked for me
Hey below code will give you some basic ideas how it works in Material Table , there are some other ways to do as well.
import MaterialTable from "material-table"; import React, { useEffect, useState } from "react"; import axios from "axios"; export default function ReportTable() { const [entries, setEntries] = useState({ data: [ { id: "", date: "", description: "", totalTime: "" } ] }); const [state] = React.useState({ columns: [ { title: "Date", field: "date", type: "date" }, { title: "Description", field: "description" }, { title: "Total Hours", field: "totalTime" } ] }); useEffect(() => { axios .get("http://localhost:8080/report") .then(response => { let data = []; response.data.forEach(el => { data.push({ id: el.id, date: el.date, description: el.description, totalTime: el.totalTime }); }); setEntries({ data: data }); }) .catch(function(error) { console.log(error); }); }, []); return ( <MaterialTable title="Report Table" columns={state.columns} data={entries.data} editable={{ onRowUpdate: (newData, oldData) => new Promise(resolve => { setTimeout(() => { resolve(); const data = [...entries.data]; data[data.indexOf(oldData)] = newData; axios .put("http://localhost:8080/report", newData, { params: { id: entries.data[0].id } }) .then(res => console.log(res.data)); setEntries({ ...entries, data }); }, 600); }), onRowDelete: oldData => new Promise(resolve => { setTimeout(() => { resolve(); const data = [...entries.data]; data.splice(data.indexOf(oldData), 1); axios .delete("http://localhost:8080/report", { params: { id: entries.data[0].id } }) .then(res => console.log(res.data)); setEntries({ ...entries, data }); }, 600); }) }} /> ); }
How would you implement OnRowAdd using axios using this method? New to react haha.
Hey below code will give you some basic ideas how it works in Material Table , there are some other ways to do as well.
import MaterialTable from "material-table"; import React, { useEffect, useState } from "react"; import axios from "axios"; export default function ReportTable() { const [entries, setEntries] = useState({ data: [ { id: "", date: "", description: "", totalTime: "" } ] }); const [state] = React.useState({ columns: [ { title: "Date", field: "date", type: "date" }, { title: "Description", field: "description" }, { title: "Total Hours", field: "totalTime" } ] }); useEffect(() => { axios .get("http://localhost:8080/report") .then(response => { let data = []; response.data.forEach(el => { data.push({ id: el.id, date: el.date, description: el.description, totalTime: el.totalTime }); }); setEntries({ data: data }); }) .catch(function(error) { console.log(error); }); }, []); return ( <MaterialTable title="Report Table" columns={state.columns} data={entries.data} editable={{ onRowUpdate: (newData, oldData) => new Promise(resolve => { setTimeout(() => { resolve(); const data = [...entries.data]; data[data.indexOf(oldData)] = newData; axios .put("http://localhost:8080/report", newData, { params: { id: entries.data[0].id } }) .then(res => console.log(res.data)); setEntries({ ...entries, data }); }, 600); }), onRowDelete: oldData => new Promise(resolve => { setTimeout(() => { resolve(); const data = [...entries.data]; data.splice(data.indexOf(oldData), 1); axios .delete("http://localhost:8080/report", { params: { id: entries.data[0].id } }) .then(res => console.log(res.data)); setEntries({ ...entries, data }); }, 600); }) }} /> ); }Worked like a charm. Thank you
@dmtx97 This is how I did it.
onRowAdd: (newData) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
const data = [...state.data];
console.log(data);
const payload = {
foo: newData.foo,
bar: newData.bar,
};
axios
.post(url, payload, {
headers: {
token: token,
},
})
.then((res) => {
console.log(res.data.data);
const resData = [...data, res.data.data];
setState({ ...state, data: resData });
});
}, 600);
}),
excelente me funciono
anyone knows how to work on useQuery apollo?
interface Row {
id: string;
username: string;
email: string;
password: string;
}
interface StaffData {
allStaff: Row[];
}
interface TableState {
columns: Array
datas: Row[];
}
const GET_STAFF = gql
query getStaff{
allStaff{
id
username
email
password
}
};
export default function Customer() {
const [state, setState] = React.useState
columns:
[
{ title: 'Id', field: 'id', type: 'numeric' },
{ title: 'Name', field: 'name' },
{ title: 'Email', field: 'email' },
{ title: 'Password', field: 'password' }
],
datas:
[
{ id: "1", username: 'Bryan', email: "[email protected]", password: "123" },
{ id: "2", username: 'Colin', email: "[email protected]", password: "123" }
]
});
const { /* loading, error, */ data } = useQuery
useEffect(() => {
console.log("useEffect hook is called");
setState((prevState) => {
const current = [...prevState.datas];
current.push();
return { ...prevState, current };
});
}, [data]);
return (
editable={{
onRowAdd: (newData) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
setState((prevState) => {
const data = [...prevState.datas];
data.push(newData);
return { ...prevState, data };
});
}, 600);
}),
onRowUpdate: (newData, oldData) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
if (oldData) {
setState((prevState) => {
const data = [...prevState.datas];
data[data.indexOf(oldData)] = newData;
return { ...prevState, data };
});
}
}, 600);
}),
onRowDelete: (oldData) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
setState((prevState) => {
const data = [...prevState.datas];
data.splice(data.indexOf(oldData), 1);
return { ...prevState, data };
});
}, 600);
}),
}}
/>
</div>
);
}
@fazaal97 how to set remote data with page
guys can some share there delete route in the back end
i am trying to connect it to by backend but it is not showing
app.delete('/api/delPrograms/:cou_id',(req,res)=>{
const Cname = req.params.cou_id;
const sqlDelete = "DELETE FROM courses WHERE cou_id = ?";
connection.query(sqlDelete, Cname, (err, result)=>{
if (err) {console.log(err);}
});
})
thats my code for the backend
Most helpful comment
Hey below code will give you some basic ideas how it works in Material Table , there are some other ways to do as well.
```
import MaterialTable from "material-table";
import React, { useEffect, useState } from "react";
import axios from "axios";
export default function ReportTable() {
const [entries, setEntries] = useState({
data: [
{
id: "",
date: "",
description: "",
totalTime: ""
}
]
});
});
setEntries({ data: data });
})
.catch(function(error) {
console.log(error);
});
}, []);
);
}