Redux 入門教程—17異步與 promise

https://github.com/pburtchaell/redux-promise-middleware/blob/master/docs/introduction.md

http://es6.ruanyifeng.com/#docs/promise

http://liubin.org/promises-book/

https://segmentfault.com/a/1190000007248878

actions/index.js

import axios from 'axios';
import { INCREMENT, DECREMENT } from '../constants';
import { FETCH_USER_SUCCESS, FETCH_USER_REQUEST, FETCH_USER_FAILURE } from '../constants';
import { LOAD_USER } from '../constants';

export const increment = () => {
  // return dispatch => {
  //   setTimeout(() => {
  //     dispatch({
  //       type: INCREMENT
  //     });
  //   }, 2000);
  // };
  return {
    type: INCREMENT,
    payload: new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("rails365");
      });
    })
  }
};

export const decrement = () => {
  return {
    type: DECREMENT
  }
};

export const get_user = () => {
  // return dispatch => {
  //   dispatch(fetch_user_request())
  //   axios.get("https://randomuser.me/api/")
  //     .then(res => {
  //       dispatch(fetch_user(res.data.results[0]));
  //     })
  //     .catch(error => {
  //       dispatch(fetch_user_failure(error.response.data));
  //     })
  // };
  return {
    type: LOAD_USER,
    // payload: axios.get("https://randomuser.me/api/")
    payload: {
      promise: axios.get("https://randomuser.me/api/")
    }
  };
};

export const fetch_user_failure = (error) => {
  return {
    type: FETCH_USER_FAILURE,
    error
  };
};

export const fetch_user = (user) => {
  return {
    type: FETCH_USER_SUCCESS,
    user
  }
};

export const fetch_user_request = () => {
  return {
    type: FETCH_USER_REQUEST
  }
};

reducers/user.js

import { LOAD_USER_FULFILLED, LOAD_USER_PENDING, LOAD_USER_REJECTED } from '../constants';

const initialState = {
  isFetching: false,
  error: null,
  user: {}
};

const user = (state = initialState, action = {}) => {
  switch(action.type) {
    case LOAD_USER_FULFILLED:
      return {
        isFetching: false,
        error: null,
        user: action.payload.data.results[0]
      };
    case LOAD_USER_PENDING:
      return {
        isFetching: true,
        error: null,
        user: {}
      }
    case LOAD_USER_REJECTED:
      return {
        isFetching: false,
        error: action.payload.response.data,
        user: {}
      };
    default: return state;
  }
}

export default user;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章