How to fetch data through api in redux?

2019-01-31 01:52发布

问题:

I am a beginner with reactjs/redux, could not find a simple to use example of how to use an api call to retrieve data in a redux app. I guess you could use a jquery ajax call but there are probable better options out there?

回答1:

JSfiddle; http://jsfiddle.net/cdagli/b2uq8704/6/

It uses redux, redux-thunk and fetch.

Fetch methods;

function fetchPostsWithRedux() {
    return (dispatch) => {
    dispatch(fetchPostsRequest());
    return fetchPosts().then(([response, json]) =>{
        if(response.status === 200){
        dispatch(fetchPostsSuccess(json))
      }
      else{
        dispatch(fetchPostsError())
      }
    })
  }
}

function fetchPosts() {
  const URL = "https://jsonplaceholder.typicode.com/posts";
  return fetch(URL, { method: 'GET'})
     .then( response => Promise.all([response, response.json()]));
}

Actions used above:

(Note: You can define many actions e.g. fetchPostRequest can be used to display a loading indicator. Or you can dispatch different actions in case of different HTTP status codes.)

function fetchPostsRequest(){
  return {
    type: "FETCH_REQUEST"
  }
}

function fetchPostsSuccess(payload) {
  return {
    type: "FETCH_SUCCESS",
    payload
  }
}

function fetchPostsError() {
  return {
    type: "FETCH_ERROR"
  }
}

And in your reducer you can load the posts to state;

const reducer = (state = {}, action) => {
  switch (action.type) {
    case "FETCH_REQUEST":
      return state;
    case "FETCH_SUCCESS": 
      return {...state, posts: action.payload};
    default:
      return state;
  }
} 

You can access the state and actions within your component after connecting them with;

connect(mapStateToProps, {fetchPostsWithRedux})(App);


回答2:

Create an action where you perform the request to your API. You can use a library like axios or fetch which return a promise.

actions/index.js:

import axios from 'axios';

export const FETCH_SOMETHING= 'FETCH_SOMETHING;
const ROOT_URL = 'http://api.youapi.com';

export function fetchWeather(city) {

    const url = `${ROOT_URL}&q=${aParamYouMayNeed}`;
    const request = axios.get(url);

    return {
        type: FETCH_SOMETHING,
        payload: request
    };
}

Then in a reducer, consume the promise result once resolved as follows:

reducers/reducer_something.js:

import { FETCH_SOMETHING} from '../actions/index';

export default function(state = [], action) {
    switch (action.type) {
        case FETCH_SOMETHING:
        return [ action.payload.data, ...state ];
    }

    return state;
}

Code borrowed from Stephen Grider. This is his repo: https://github.com/StephenGrider/ReduxCasts/tree/master/weather/src