Search code examples
reactjsreact-reduxreact-hooksreact-modal

How to fetch data only when the modal loads


I have a react component let's say: app.js ( parent component ) that has a child component which renders a react bootstrap modal component. the parent component fetch data from redux using react hook like that:

  useEffect(() => { props.dispatch(actions.loadAll());},[]);

and then data are being passed to show in my modal component. I am handling the modal visibility with "show" and "onShow" state. Is there anyways, I can avoid loading the data in my parent component and loads only after the modal component loads and display data there? any suggestions would be appreciated.


Solution

  • You can use useEffect hook that depends on your state show.

    useEffect(() => { props.dispatch(actions.loadAll());},[show]);
    

    Using this chunk of code when the show state changes, the useEffect runs. So when your modal opens, your data is loaded.