N
N
Nikolai Antonov2016-11-08 00:54:56
React
Nikolai Antonov, 2016-11-08 00:54:56

How to put 2 redux thunk on different reducers?

There are several reducers that are combined into 1 using combineReducers. How to put thunk middleware on only 2 of them separately? In the store, in the applyMiddleware method, you can add a middleware for everything. And how to separate processing logic?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Максим, 2016-11-08
@maxfarseer

I did not quite understand your question, but thunk middleware does not affect the reducer in any way.
Redux-thunk is just a helper function for your action-crackers (or just actions, whichever is more convenient). If you look at the source code , then you can describe it like this: if AC (action, action crator, action creator ...) returns a simple object - throw it further, if it returns a function, then "throw" the dispatch and getState functions into this function in as arguments. For example, this gives us the ability to work with asynchronous requests. Since, in order to reach the reducer, we must use the dispatch function. And if there was no redux-thunk, then where would it come from in our action code: there is no import to the file, nowhere is it described what const dispatch = ...?
I'll give an example :

export function logout {
  return {
    type: LOGOUT_SUCCESS,
  }
}

AC returns a simple object, which (if there are no other middleware affecting the work) immediately gets into the reducer.
export function login(data) {
  return dispatch => {
    dispatch({ type: LOGIN_REQUEST })

    return request.post(`${API_ROOT_V1}/auth/signin`)
      .send(data)
      .then(res => {
        if (!res.ok) {
          dispatch({ type: LOGIN_FAILURE })
          dispatch(showNotification({
            status: 'err',
            text: 'something going wrong',
          }))

        } else {
          dispatch({
            type: LOGIN_SUCCESS,
            data: res.body.data,
          })
          localStorage.setItem('cks_token', res.body.data)
          dispatch(push('/'))
        }
      }, err => {
        dispatch({ type: LOGIN_FAILURE })
        dispatch(showNotification({
          status: 'err',
          text: err.body && err.body.error || err.message,
        }))
      })
  }
}

Special attention to return dispatch => {- this means that AC returns a function, and therefore dispatch is available in this function due to redux-thunk. If the ES2015 syntax is misleading, then this could be written as return function(dispatch) {...
PS Describe in more detail what you mean by "And how to separate the processing logic?"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question