简体   繁体   中英

Side Effects in Redux & React RxJS

Where should you put the API-calls in Redux ?

I think they belong in Actions because they are part of the data and don't have side-effects.

Does that sound right?

I want to avoid RxJS or ReduxSaga.

I make my API calls in my action file but have a separate function that creates the action itself. Regardless I am agreeing with you in that API Calls work best (in our collective opinion) alongside action creators.

Create Scenarios

  1. If you call a synchronous API just in a single component, you can make your API call in actions, get the data back, and then dispatch. Simple is that.
  2. If you call a synchronous API in multiple components, You will handle them all separately?
  3. If you call a asynchronous API, You will dispatch a flag when the request began and again dispatch a flag when request complete?

For point 2,3 Thunk middleware is the best option as it is much easier than Saga.

This is a can of worms in the redux world and there are many approaches. The main idea is to execute functions that have access to the store's dispatch method so that these functions can orchestrate their own sequence of actions to the store. However, each approach dresses up the function execution and the inherent statefulness of side effects (eg waiting for an API call to finish before dispatching the “done” action to the store) in a different way:

  • The imperative solution is thunks which are just plain old functions. When the store receives a thunk, instead of running the thunk through the reducer like a regular object action, the store executes the thunk while passing the store's dispatch function so that the thunk can orchestrate its own sequence of actions. See redux-thunk for an example.

  • redux-saga is a declarative solution where you dispatch action objects that describe how the side effect is to be carried out. For example, if the side effect is fetching from an API then the action contains the fetch function and the arguments to be passed to the fetch function. For example, if the fetch call is fetchFromServer(a, b, c) then the action you dispatch contains fetchFromServer , a , b and c . The stateful part of the side effects is kept inside generator functions called “sagas”.

  • redux-observable is another declarative solution but instead of using generators for “statefulness”, it uses observables. Observables can be a bit non-intuitive so I won't go much into it here but it is the solution that I used. Honestly, the latter two are, to some extent, two sides of the same coin but I find observables a more elegant abstraction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM