makerequest ajax,reactjs - How to make AJAX request in redux - Stack Overflow

You might want to separate concerns, to keep action creators "pure".

Solution; write some middleware. Take this for example (using superagent).

import Request from 'superagent';

const successHandler = (store,action,data) => {

const options = action.agent;

const dispatchObject = {};

dispatchObject.type = action.type + '_SUCCESS';

dispatchObject[options.resourceName || 'data'] = data;

store.dispatch(dispatchObject);

};

const errorHandler = (store,action,err) => {

store.dispatch({

type: action.type + '_ERROR',

error: err

});

};

const request = (store,action) => {

const options = action.agent;

const { user } = store.getState().auth;

let method = Request[options.method];

method = method.call(undefined, options.url)

if (user && user.get('token')) {

// This example uses jwt token

method = method.set('Authorization', 'Bearer ' + user.get('token'));

}

method.send(options.params)

.end( (err,response) => {

if (err) {

return errorHandler(store,action,err);

}

successHandler(store,action,response.body);

});

};

export const reduxAgentMiddleware = store => next => action => {

const { agent } = action;

if (agent) {

request(store, action);

}

return next(action);

};

Put all this in a module.

Now, you might have an action creator called 'auth':

export const auth = (username,password) => {

return {

type: 'AUTHENTICATE',

agent: {

url: '/auth',

method: 'post',

resourceName: 'user',

params: {

username,

password

}

}

};

};

The property 'agent' will be picked up by the middleware, which sends the constructed request over the network, then dispatches the incoming result to your store.

Your reducer handles all this, after you define the hooks:

import { Record } from 'immutable';

const initialState = Record({

user: null,

error: null

})();

export default function auth(state = initialState, action) {

switch (action.type) {

case 'AUTHENTICATE':

return state;

case 'AUTHENTICATE_SUCCESS':

return state.merge({ user: action.user, error: null });

case 'AUTHENTICATE_ERROR':

return state.merge({ user: null, error: action.error });

default:

return state;

}

};

Now inject all this into your view logic. I'm using react as an example.

import React from 'react';

import ReactDOM from 'react-dom';

/* Redux + React utils */

import { createStore, applyMiddleware, bindActionCreators } from 'redux';

import { Provider, connect } from 'react-redux';

// thunk is needed for returning functions instead

// of plain objects in your actions.

import thunkMiddleware from 'redux-thunk';

// the logger middleware is useful for inspecting data flow

import createLogger from 'redux-logger';

// Here, your new vital middleware is imported

import { myNetMiddleware } from '';

/* vanilla index component */

import _Index from './components';

/* Redux reducers */

import reducers from './reducers';

/* Redux actions*/

import actionCreators from './actions/auth';

/* create store */

const store = createStore(

reducers,

applyMiddleware(

thunkMiddleware,

myNetMiddleware

)

);

/* Taint that component with store and actions */

/* If all goes well props should have 'auth', after we are done */

const Index = connect( (state) => {

const { auth } = state;

return {

auth

};

}, (dispatch) => {

return bindActionCreators(actionCreators, dispatch);

})(_Index);

const provider = (

);

const entryElement = document.getElementById('app');

ReactDOM.render(provider, entryElement);

All of this implies you already set up a pipeline using webpack,rollup or something, to transpile from es2015 and react, to vanilla js.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值