Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux saga - the point to skip API requsts if data already exists in redux store

I am working on the project with usage of redux-saga and I have one question to ask you. I tried to find an answer on my question nearly for two days with power of Google but it did not help.

We have some function that is triggered by saga on each FETCH_REQUEST action.

export function* fetchData(action) {
  try {
    const usersList = (yield select()).usersList;

    // makes API call only if there is no users found in the current state
    if(!usersList) {
      const data = yield call(Api.fetchUser)
    }

    yield put({type: "FETCH_SUCCEEDED", usersList})
  } catch (error) {
    yield put({type: "FETCH_FAILED", error})
  }
}

On success the FETCH_SUCCEEDED action is triggered and we save received data to the state. But it seems to me that the decision making point "to make or not the API call" is not in the right place. The current approach causes spawning of some amount of actions that are useless and skipped in sagas. In case when some others sagas subscribed on the _REQUEST actions they triggers another useless actions and so on.

So the question is - What is the 'best practice' place to check whether the data needs to be loaded from API or ReduxStore?

like image 728
Vasiliy Ditsyak Avatar asked Oct 30 '22 01:10

Vasiliy Ditsyak


1 Answers

I assume that you dispatch FETCH_REQUEST action creator from your component. This component probably receives userList as a property. So this component is the best place to determine whether FETCH_REQUEST action should be dispatched.

Something like this:

class MyComponent extends React.Component {
  componentDidMount() {
    if (!this.props.userList) {
      this.props.fetchData();
    }
  }
}

...

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);

In this case you don't need to use a selector and extra condition in your saga.

like image 88
quotesBro Avatar answered Nov 09 '22 16:11

quotesBro