React Redux Tutorials - 12 - Async Actions

jh22j9·2020년 10월 13일
0

React Redux Tutorials

목록 보기
12/20

Actions


Synchronous Actions

  • as soon as an action was dispatched, the state was immediatly updated.
  • if you dispatch the BUY_CAKE action, the numOfCakes was right away decremented by 1.
  • same with BUY_ICECREAM action as well.

Async Actions

  • Asynchronous API calls to fetch data from an end point and use that data in the application.

Our Application will fetch a list of users from an API endpoint and stores it in the redux store.

State


// typical form of state with data fetching
state = {
  loading: true,
  data: [],
  error: ''
}

Actions


FETCH_USERS_REQUEST - fetch list of users
FETCH_USERS_SUCCESS - fetched successfully
FETCH_USERS_FAILURE - Error fetching the data

Reducer


  • case: FETCH_USERS_REQUEST
    loading: true
  • case: FETCH_USERS_SUCCESS
    loading: false
    users: data (from API)
  • case: FETCH_USERS_FAILURE
    loading: false
    error: error (from API)

Set up to understand about Async Action


const redux = require('redux'); // (4)
const createStore = redux.createStore; // (4)

// (1) define a state
const initialState = {
  loading: false,
  users: [],
  error: ''
};

// (2) declare the constants for the action types and define action creators
const FETCH_USERS_REQUEST = 'FETCH_USERS_REQUEST';
const FETCH_USERS_SUCCESS = 'FETCH_USERS_SUCCESS';
const FETCH_USERS_FAILURE = 'FETCH_USERS_FAILURE';

const fetchUsersRequest = () => {
  return {
    type: FETCH_USERS_REQUEST
  }
};

const fetchUsersSuccess = users => {
  return {
    type: FETCH_USERS_SUCCESS,
    payload: users
  }
};

const fetchUsersFailure = error => {
  return {
    type: FETCH_USERS_FAILURE,
    payload: error
  }
};

// (3) define reducer functions
const reducer  = (state = initialState, action) => {
  switch(action.type) {
    case FETCH_USERS_REQUEST:
      return {
        ...state,
        loading: true
      }
    case FETCH_USERS_SUCCESS:
      return {
        loading: false,
        users: action.payload,
        error: ''
      }
    case FETCH_USERS_FAILURE:
      return {
        loading: false,
        users: [],
        error: action.payload
      }
  }
}

// (4) create a redux store
const store = createStore(reducer);

0개의 댓글

관련 채용 정보