I have the below code, where it pull all data from server as API
export const apiExpenses = () => {
//Get All Expenses, Realtime
const { data: tableDataExpenses, error, mutate } = useSWR('/api/expenses/datatable', () =>
axios
.get('/api/expenses/datatable')
.then(res => res.data),
)
return {
tableDataExpenses,
}
}
And using the output of that API in another component with useEffect
const { tableDataExpenses } = apiExpenses();
const [expenses, setExpenses] = useState([]);
useEffect(() => {
setExpenses(tableDataExpenses.data);
return () => {
setExpenses([]);
};
}, [tableDataExpenses]);
But I am ending in below errors,
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
And because of this, I can’t get the value of tableDataExpenses
If I remove setExpenses
from useEffect there are no errors and again if I write setExpenses
it loads data.
But again in the next render, it fails with error.
So How can I prevent this error with the cleanup function?