Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining Redux actions

I am new to React, Redux and JS overall. I want to know how can I dispatch and action after another is finished - Promises in correct way. My code actually works but it keeps throwing error:

readingActions.js?14b9:56 Uncaught (in promise) TypeError: dispatch(...).then is not a function(…)

This is my setup.

  • This is my action creator what I want chained action and where warning happends.

    export function createReading(reading) {
      return function (dispatch) {
        dispatch({type: CREATE_READING});
        return request(
          `${API_URL}new`, {method: 'POST', body:JSON.stringify(reading)},
          (json) => {( dispatch({type: CREATE_READING_SUCCESS, res: json}).then(dispatch(Notifications.success(showSuccess(json.book.title)))))},
          (json) => { dispatch({type: CREATE_READING_ERROR400, res: json}).then(dispatch(Notifications.error(showError(json.error)))) },
          (res) => { dispatch({type: CREATE_READING_ERROR500, res: res}) },
          (ex) => { dispatch({type: CREATE_READING_FAILURE, error: ex}) },
        )
      }
    }
    

As you can see the problem is in .then, since I dont know how to trigger action correctly.

  • You can also see request that is my helper function that looks like so (here I append token, return different responses):

    export function request(url, options, success, error400, error, failure) {
        let headers = new Headers();
        headers.append("Content-Type", "application/json")
        headers.append("Accept", "application/json")
        options["headers"] = headers;
    
         if (localStorage.jwtToken) {
            let token = localStorage.jwtToken;
            headers.append('Authorization', 'JWT '+token);
         }
    
        return fetch(url, options)
            .then(res => {
                if (res.status >= 200 && res.status < 300) {
                    res.json().then(json => {
                         return success(json)
                    })
                } else if (res.status === 400) {
                    res.json().then(json => {
                        return error400(json)
                    })
                } else {
                    return error(res)
                }
            }).catch((ex) => {
                return failure(ex)
            })
    }
    

Question is how can I execute proper .then and what would be the correct way?

like image 656
alphiii Avatar asked Dec 17 '16 16:12

alphiii


1 Answers

If you want to dispatch actions in chains you can actually implement it on your own.

Now say after analysing a bit you take a pen and paper and start write basic algorithm for how it should work and you come up with following:-

dispatch(action) => action returns function => action returns function => action returns an object(here you chain ends)

Now from above if you see that you create a middleware and keep on dispatching actions which return functions until you get an action with returns an object. This is what redux-thunk does.

So even if you try to create something of your own do that for your learning, but eventually you will come up with something like thunk or maybe some other package.

I would really say give redux-thunk a try.Also for middleware understanding I would recommend you can check redux middleware docs.

like image 123
Harkirat Saluja Avatar answered Oct 03 '22 20:10

Harkirat Saluja