Defining asynchronous action creators

The next step is defining an asynchronous action creator for the fetchTodos action. Here, we are going to use the async/await construct.

We are now going to use an async function to define the fetchTodos action creator:

  1. In src/actions.js, first import the FETCH_TODOS action type and the fetchAPITodos function:
import {
FETCH_TODOS, ADD_TODO, TOGGLE_TODO, REMOVE_TODO, FILTER_TODOS
} from './actionTypes'
import { fetchAPITodos } from './api'
  1. Then, define a new action creator function, which will return an async function that is going to get the dispatch function as an argument:
export function fetchTodos () {
return async (dispatch) => {
  1. In this async function, we are now going to call the API function, and dispatch our action:
        const todos = await fetchAPITodos()
dispatch({ type: FETCH_TODOS, todos })
}
}

As we can see, asynchronous action creators return a function that will dispatch actions at a later time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.131.238