Search code examples
react-nativereduxredux-thunk

Redux Thunk vs Making api call in react component


I was wondering if what I've been doing in my ReactNative/Redux application is wrong. This is how I've been handling async actions.

MyComponent.js

componentDidMount() {
  fetch('https://www.mywebsite.com')
  .then(data => this.props.handleApiSuccess(data)) // injected as props by Redux
  .catch(err => this.props.handleApiError(err)); // injected as props by Redux
}

The redux-thunk way I should probably be doing

export const handleApiCall = () => dispatch => {
  fetch('https://www.mywebsite.com')
  .then(data => dispatch(handleApiSuccess(data)))
  .catch(err => dispatch(handleApiError(err)));
}

Is there anything wrong with the way its being done in the first part?


Solution

  • There is nothing wrong in terms of bugs: the code will work and serve its purpose.

    But in terms of design it has huge flaw: coupling. Merging your fetching logic inside the Components may cause complications as your app will grow.

    What if your way of fetching will change, e.g. you'll decide to communicate with server via websockets? What if your way of handling of server response will change, i.e. handleApiError will have to be replaced with something else? What if you'll decide to reuse same fetching in the different part of your app?

    In all these cases you'll have to alter your existing Components which ideally shouldn't be affected by such logic changes.