'React table is not updating after new row added
Hi i'm using axios to add a new record and i am trying to update the table after any CRUD operations on the database.
The parent component has MailList and AddMail components. AddMail component has a form control that calls axios POST to add a new record. How do i refresh the table in MailList using react hooks?
export default function MailList() {
const [mailList, setMailList] = useState([]);
useEffect(() => {
axios.get("http://localhost:5243/api/Mail")
.then(res => {
setMailList(res.data)
console.log(res.data)
})
.catch(err => console.log(err))
}, []);
return(
<React.Fragment>
<Title>Recent Mail Scanned</Title>
<Table>
<TableHead>
<TableRow>
<TableCell>ID</TableCell>
<TableCell>Tracking Number</TableCell>
<TableCell>Date Scanned</TableCell>
</TableRow>
</TableHead>
<TableBody>
{mailList.map((m) => (
<TableRow key={m.mailId}>
<TableCell>{m.mailId}</TableCell>
<TableCell>{m.trackingNo}</TableCell>
<TableCell>{m.dateScanned}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</React.Fragment>
);
}
AddMail
const initialValues = {
trackingNumber: '',
dateCreated: new Date(),
}
const [values, setValues] = useState(initialValues);
const handleInputChange = e => {
const { name, value } = e.target
setValues({
...values,
[name]: value
})
}
let item = {
trackingNo: values.trackingNumber,
dateCreated: values.dateCreated
}
function addMail()
{
axios.post("http://localhost:5243/api/Mail", item )
}
...
<Button onClick={addMail}>Save Mail</Button>
Solution 1:[1]
You want to add like this in useEffect.
useEffect(()=>{
'your code'
},[mailList])
Solution 2:[2]
You must give your useEffect a dependency. Then if there are any changes in the maillist then the page should be changed.
const [mailList, setMailList] = useState([]);
useEffect(() => {
axios.get("http://localhost:5243/api/Mail")
.then(res => {
setMailList(res.data)
console.log(res.data)
})
.catch(err => console.log(err))
}, [mailList]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rakesh mokariya |
| Solution 2 | kazi naeem rayhan |
