reading-notes

Redux - Asynchronous Actions

Review, Research, and Discussion

should only depend on their state and action arguments

Using switch

Document the following Vocabulary Terms

Preparation Materials

Async Logic and Data Fetching

By itself, a Redux store doesn’t know anything about async logic. It only knows how to synchronously dispatch actions, update the state by calling the root reducer function, and notify the UI that something has changed. Any asynchronicity has to happen outside the store.

Some common kinds of side effects are things like

Using Middleware to Enable Async Logic

Let’s look at a couple examples of how middleware can enable us to write some kind of async logic that interacts with the Redux store.

One possibility is writing a middleware that looks for specific action types, and runs async logic when it sees those actions, like these examples:

import { client } from '../api/client'

const delayedActionMiddleware = storeAPI => next => action => {
  if (action.type === 'todos/todoAdded') {
    setTimeout(() => {
      // Delay this action by one second
      next(action)
    }, 1000)
    return
  }

  return next(action)
}

const fetchTodosMiddleware = storeAPI => next => action => {
  if (action.type === 'todos/fetchTodos') {
    // Make an API call to fetch todos from the server
    client.get('todos').then(todos => {
      // Dispatch an action with the todos we received
      dispatch({ type: 'todos/todosLoaded', payload: todos })
    })
  }

  return next(action)
}

Redux Async Data Flow

ex

Redux Thunk

Thunk is a programming concept where a function is used to delay the evaluation/calculation of an operation.