Search code examples
reactjsangularreduxfetchstore

How to fetch data that needs to be fetched only once


I want to fetch data from an API endpoint, but I don't need to fetch it again when I come back to the screen or component again.

For example, I need a config, which determines the layout of a modal dialog, and I want to get it only when we open the dialog. And for the next time, we open the dialog, I don't need to fetch config again.

I need solutions both for React/Redux and Angular 6+.


Solution

  • In react, you could do it like this:

    Redux state

    {
      MODAL_CONFIG: null   // INITIAL STATE AS null
    }
    

    YourModal.js

    // INSIDE YOUR MODAL COMPONENT
    
    const dispatch = useDispatch();  // FROM react-redux
    const MODAL_CONFIG = useSelector((state) => state.MODAL_CONFIG); // FROM react-redux
    
    useEffect(() => {                            // EFFECT TO FETCH API
      if (MODAL_CONFIG === null) {               // WILL ONLY FETCH API IF MODAL_CONFIG STATE IS null
        fetchApiForConfig().then((data) => 
          dispatch(
            type: "UPDATE_MODAL_CONFIG",
            payload: {config: data}
          );
        );
      }
    },[dispatch,MODAL_CONFIG]);
    
    return(
      MODAL_CONFIG ?
        <YourModalUI/>    // IF MODAL_CONFIG EXISTS. DISPLAY MODAL
      : <SomeSpinner/>    // ELSE DISPLAY SPINNER
    );
    

    reducer.js

    function reducer(state,action) {
      switch(action.type) {
        case "UPDATE_MODAL_CONFIG": {
          return({
            ...state,
            MODAL_CONFIG: action.payload.config
          });
        }
        default: {
          return state;
        }
      }
    }
    

    Lots of room for improvements, but this is basically what you need to do.