JamesG
JamesG

Reputation: 2018

Where to add server request functions in React-Redux

I have the following Axios request:

componentDidMount() {
    axios.post('http://localhost:3030/api/weather/refresh').then(response => {
      store.dispatch(refreshWeather(response))
    });
  }

This sends a dispatch to Redux which is used to feed the presentational container in the common pattern.

My question is - how can I make it do this axios.post() request is re-usable in other components or parts of the app? I have got as far as having it in an external file which is imported, but is there a better way to structure my project so all axios requests are grouped together?

I have the following mapDispatchToProps:

const mapDispatchToProps = (dispatch, ownProps) => {    
  return {
    onClickRefresh: () => {
      dispatch(refreshWeather(arr))
    }
  }
}

And I want to run the same request as the componentDidMount(), but not sure of the best way to make re-usable as explained above.

Thanks

Upvotes: 0

Views: 445

Answers (3)

yachaka
yachaka

Reputation: 5569

config.js

module.exports = {
  API_URL: 'http://localhost:3030/api',
};

makeRequest.js

import axios from 'axios';
import { API_URL } from './config';

module.exports = (path, method, ...args) => axios[method](API_URL + path, ...args);

actions.js

module.exports.refreshWeather = (newWeather) => ({
  type: 'REFRESH_WEATHER',
  payload: newWeather,
});

stories.js

import makeRequest from './makeRequest';
import { refreshWeather as refreshWeatherAction } from './actions';

module.exports.resfreshWeatherStory = (dispatch) => (
    makeRequest('/weather/refresh', 'post')
        .then(response => dispatch(refreshWeatherAction(response)));
);

YourComponent.js

...
import { refreshWeatherStory } from './stories';
...
componentDidMount() {
    refreshWeatherStory(store.dispatch);
}
...

OtherPlace.js

...
import { refreshWeatherStory } from './stories';

const mapDispatchToProps = dispatch => ({
    onClickRefesh: () => refreshWeatherStory(dispatch),
});
...

You get the idea

Upvotes: 1

Ben Bud
Ben Bud

Reputation: 16980

You can accomplish this by applying the redux-thunk middleware and having an intermediary method perform the request.

const REFRESH_WEATHER = 'REFRESH_WEATHER';

export const requestWeather = () => dispatch => {
    axios.post('http://localhost:3030/api/weather/refresh').then(response => {
        dispatch(refreshWeather(response));
    });
};

const refreshWeather = (response) => {
    return {
        type: REFRESH_WEATHER,
        response,
    };
}

If you find yourself making a lot of repetitive similar requests you can build out your own api middleware to handle any requests.

Upvotes: 2

Laith Azer
Laith Azer

Reputation: 619

The pattern in Redux is to use an Async Action Creator, that way it can be re-used just like any other Action Creator and mapped to your props.

There is a good example in the official docs of how this is done.

Upvotes: 1

Related Questions