Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch data through api in redux?

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?

like image 823
bier hier Avatar asked Oct 02 '16 04:10

bier hier


People also ask

How do I get fetch value from Redux?

Save Redux store objects to external JSON file. STEP-1 import useStore first from react-redux and then getState() function is used to access store state. STEP-2 area is the name of my slice in Redux store and areaName is state in that slice. STEP-3 FiletoSave variable is used to export JSON file with data from store.


2 Answers

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); 
like image 161
cdagli Avatar answered Nov 12 '22 19:11

cdagli


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

like image 36
Franco Avatar answered Nov 12 '22 19:11

Franco