Updating the state of the Home Page component from a IonModal getting a useEffect error

Viewed 40

I have an IonModal that I'm using to add data to my database through an API call. I will then add the response data to a list in my Redux store which is being displayed on the Home Page.

This function is being called on a button press within my modal to call the API, get the response, add it to the store, and close the modal:

const addData = async () => {
  const transaction = await createTransaction(data);
  dispatch(addTransaction(transaction));
  setShowModal(false);
};

createTransaction is calling the API and returning the response data.

When it is called and the modal is closed I am getting this error

Warning: 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.

In my Home page all I have is a simple useEffect that sets the state within the component to the state within the redux store and should update displayed content within the component but isn't:

const transactions = useSelector(state => state.transactions);
const [data, setData] = useState([]);

useEffect(() => {
  setData(transactions);
}, [transactions]);

The data does get successfully added to the Redux Store but it just doesn't get updated visually on the home page.

Any help or advice would be very much appreciated.

1 Answers

Try adding data to the useEffect array like so: useEffect(() => {}, [transactions, data]). Essentially what the useEffect hook does is re-render each time it senses a change in a state variable. So your data state variable is getting updated; however, it's not being updated visually because it's not being told to rerender on the data change.

Related