Search code examples
reactjsreduxreact-reduxreact-router-redux

Where should I load data from server in Redux + ReactJS?


For example I have two components - ListOfGroupsPage and GroupPage.

In ListOfGroupsPage I load list of groups from the server and store it to the state.groups

In route I have mapping like ‘group/:id’ for GroupPage

When this address is loaded, the app shows GroupPage, and here I get the data for group from state.groups (try to find group in state via id). All works fine.

But if I reload page, I'm still on page /group/2, so GroupPage is shown. But state is empty, so the app can't find the group.

What is the proper way to load data in React + Redux? I can see this ways:

1) Load all data in root component. It will be very big overhead from traffic side

2) Don't rely on store, try to load required data on each component. It's more safe way. But I don't think that load the same data for each component - it's cool idea. Then we don't need the state - because each component will fetch the data from server

3) ??? Probably add some kind of checking in each component - first try to find required data in store. If can't - load from the server. But it requires much of logic in each component.

So, is there the best solution to fetch data from server in case of usage Redux + ReactJS?


Solution

  • One approach to this is to use redux-thunk to check if the data exist in the redux store and if not, send a server request to load the missing info.

    Your GroupPage component will look something like

    class GroupPage extends Component {
      componentWillMount() {
        const groupId = this.props.params.groupId
        this.props.loadGroupPage(groupId);
      }
      ...
    }
    

    And in your action...

    const loadGroupPage = (groupId) => (dispatch, getState) => {
      // check if data is in redux store
      // assuming your state.groups is object with ids as property
      const {
        groups: {
          [groupId]: groupPageData = false
        }
      } = getState();
    
      if (!groupPageData) {
        //fetch data from the server
        dispatch(...)
      }
    }