Sergei Mikhailovskii
Sergei Mikhailovskii

Reputation: 2465

How to fetch data from server with redux?

I need to fetch data from server with the help of such instrument as Redux. I watched some tutorials about it and wrote some code for it. Here it is:

actions/fetching_actions.js

import * as Actions from '../constants/action_types';

function fetchListOfCities() {
  return fetch(`${Actions.BASE_URL}/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=8df903ce56f6d18245e72f380beb297d`);
}

export const listOfCitiesRequest = () => function (dispatch) {
  return fetchListOfCities()
    .then(list => list.json())
    .then((list) => {
      dispatch(getListOfCities(list));
    }).catch((error) => {
      console.log(error);
    });
};

export const getListOfCities = result => ({
  type: Actions.LIST_RESPONSE,
  result,
});

constants/action_types.js

export const BASE_URL = 'http://api.openweathermap.org';

export const LIST_RESPONSE = 'LIST_RESPONSE';

export const CITY_RESPONSE = 'CITY_RESPONSE';

reducers/fetching_reducer.js

import * as Actions from '../constants/action_types';

const initialState = {
  list: [],
  city: {},
};

const FETCHING_REDUCER = (state = initialState, action) => {
  switch (action.type) {
    case Actions.LIST_RESPONSE:
      return {
        ...state,
        list: action.result,
      };
    case Actions.CITY_RESPONSE:
      return {
        ...state,
        city: action.result,
      };
    default:
      return state;
  }
};

export default FETCHING_REDUCER;

reducers/index.js

import * as Actions from '../constants/action_types';

const initialState = {
  list: [],
  city: {},
};

const FETCHING_REDUCER = (state = initialState, action) => {
  switch (action.type) {
    case Actions.LIST_RESPONSE:
      return {
        ...state,
        list: action.result,
      };
    case Actions.CITY_RESPONSE:
      return {
        ...state,
        city: action.result,
      };
    default:
      return state;
  }
};

export default FETCHING_REDUCER;

And unfortunately I don't know what should I do further. Before I fetched data in this way in Component:

getCitiesListFromApiAsync = async () => {
     const fetchData = await fetch('http://api.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=8df903ce56f6d18245e72f380beb297d').then();
     const data = await fetchData.json();

     if (data.cod !== '200') {
       Alert.alert('Loading failed');
     } else {
       this.setState({ data });
     }
   };

But I heard that it's better to fetch data by redux, so, please, can you explain me how to finish this fetching part, what should I add here?

Upvotes: 3

Views: 1171

Answers (2)

befev
befev

Reputation: 71

To send some request to the server via redux you should use one of middlewares:

  1. redux-thunk
  2. redux-promise
  3. redux-saga
  4. redux-observable
  5. etc.

The easiest I think is redux-thunk.

1. Install the package:

$ npm install redux-thunk

2. Connect it to your store:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

After that, you will be allowed to dispatch to redux not only a plain javascript object but also functions.

3. So you can dispatch like this:

store.dispatch(listOfCitiesRequest());

Upvotes: 0

sachin babu
sachin babu

Reputation: 162

In saga please import these things

import {  put } from 'redux-saga/effects';

getCitiesListFromApiAsync = async () => {
     const fetchData = await fetch('http://api.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=8df903ce56f6d18245e72f380beb297d').then();
     const data = await fetchData.json();

     if (data.cod !== '200') {
       Alert.alert('Loading failed');
     } else {
       yield put({ type: LIST_RESPONSE, payload: data });
     }
   };

In reducer

  switch (action.type) {
    case Actions.LIST_RESPONSE:
      return {
        ...state,
        list: action.payload,
      };

Upvotes: 1

Related Questions