I'm new to ReactJS and to JS in general.
I have a table that populates with data from an API request. Each row has a delete button that deletes that specific entry. When you press the delete button a Modal opens asking you to confirm the operation, if you click YES the DELETE request gets passed to the API, a new GET request gets asked to the API to retrieve the new updated list of elements, the Modal closes and you should see the new updated table.
Or at least, that's what should be happening.
Right now when I confirm the delete operation the Modal closes but the table doesn't update, however if I refresh the page the table shows the updated content without the deleted entry so everything seems to be working correctly except for the table not updating after confirmation.
This code works if I press F5 to manually refresh the page:
function TableCategory(prop, ref) {
const [info, setInfo] = useState([]);
useImperativeHandle(ref, () => {
return {
updateTable: () => {
fetchData();
},
};
});
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
const response = await getCategoryList(UserService.getUserToken());
let newArr = [...response.data];
setInfo(newArr);
};
Now if I try to "simulate a refresh" running fetchData() again after a delay, it works correctly and the component updates after the Modal closes without the need to manually refresh the page. I assume I'm not handling the ASYNC behavior as I should.
This code works without the need to manually refresh:
useImperativeHandle(ref, () => {
return {
updateTable: () => {
fetchData();
setTimeout(() => {
fetchData();
}, 200);
},
};
});
This is the async method performing the request to the API:
export function getCategoryList(myToken) {
return Promise.resolve(axios.get(CATEGORY_ENDPOINT, config(myToken)));
}
If there is something else you need to see, please let me know I only posted what I thought was relevant to the question.
Thanks!