I am trying to fetch data from the db asynchronously whenever a new field is updated but even after adding the necessary async and await keyword the table gets updated only on page load.
I have a form to submit data to the db and i want the table to be updated as soon as it happens
Code to update table
const entryList = []
const [tableEntries, setTableEntries] = React.useState(entryList)
useEffect(() => {
async function fetchMyAPI() {
await Axios.get('http://localhost:8080/api/connections')
.then(res => {
const newList = entryList.concat(res.data);
Array.prototype.forEach.call(newList, response => {
setTableEntries(prevTableEntries => [...prevTableEntries,response]);
});
})
.catch(err => console.log(err));
}
fetchMyAPI()
}, []);
Code to display data inside of the table
{ tableEntries.map((item) => (
<>
<tr>
<th scope="row">1</th>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.connectionType}</td>
<td>
<CDropdown className="m-1" size="lg">
<CDropdownToggle color="secondary">
Select Option
</CDropdownToggle>
<CDropdownMenu>
<CDropdownItem>Delete</CDropdownItem>
<CDropdownItem>Reauthorize</CDropdownItem>
</CDropdownMenu>
</CDropdown>
</td>
</tr>
</>
))}
Code for form submission (Including this incase this was necessary for you guys to understand)
async handleSubmit(event) {
event.preventDefault(); // stop browser from submitting form
const form = await event.target; // get form element
const article = { "connectionType": "InstagramConnection", "name": this.state.value, "accessCredentials": { "id": 2, "token": this.state.access_token } };
await Axios.post('http://localhost:8080/api/connections', article)
.then(response => console.log(response.data))
.catch(error => {
console.log('There was an error!', error);
})
}
(EDIT: Added the variables which i am using for updating the table to the code able for easier reference)
Aucun commentaire:
Enregistrer un commentaire