Skip to content

Instantly share code, notes, and snippets.

@uladzislau-stuk
Last active December 24, 2019 07:30
Show Gist options
  • Save uladzislau-stuk/f03a8d04022149b61137866bfb9fc9df to your computer and use it in GitHub Desktop.
Save uladzislau-stuk/f03a8d04022149b61137866bfb9fc9df to your computer and use it in GitHub Desktop.
[Redux Advanced Tutorial] #redux

Usually, for any API request you'll want to dispatch at least three different kinds of actions, An action informing the reducers that the:

  • request began
  • request finished successfully
  • request failed

Note You'll need to design the shape of your application's state before rushing into the implementation

by using this specific middleware, an action creator can return a function instead of an action object. This way, the action creator becomes a thunk.

When an action creator returns a function, that function will get executed by the Redux Thunk middleware. This function doesn't need to be pure; it is thus allowed to have side effects, including executing asynchronous API calls.

How include thukn?

import thunkMiddleware from 'redux-thunk'
import { createLogger } from 'redux-logger'
import { createStore, applyMiddleware } from 'redux'
import { selectSubreddit, fetchPosts } from './actions'
import rootReducer from './reducers'
const loggerMiddleware = createLogger()
const store = createStore(
  rootReducer,
  applyMiddleware(
    thunkMiddleware, // lets us dispatch() functions
    loggerMiddleware // neat middleware that logs actions
  )
)
store.dispatch(selectSubreddit('reactjs'))
store.dispatch(fetchPosts('reactjs')).then(() => console.log(store.getState()))

The nice thing about thunks is that they can dispatch results of each other

export function fetchPostsIfNeeded(subreddit) {
  // Note that the function also receives getState()
  // which lets you choose what to dispatch next.
  // This is useful for avoiding a network request if
  // a cached value is already available.
  return (dispatch, getState) => {
    if (shouldFetchPosts(getState(), subreddit)) {
      // Dispatch a thunk from thunk!
      return dispatch(fetchPosts(subreddit))
    } else {
      // Let the calling code know there's nothing to wait for.
      return Promise.resolve()
    }
  }
}

Async Flow

Asynchronous middleware like redux-thunk or redux-promise wraps the store's dispatch() method and allows you to dispatch something other than actions, for example, functions or Promises.

Middleware

It provides a third-party extension point between dispatching an action, and the moment it reaches the reducer

Articles

What async middleware should I use? How do you decide between thunks, sagas, observables, or something else?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment