redux-api icon indicating copy to clipboard operation
redux-api copied to clipboard

[Question] how to change state in responseHandler?

Open divan opened this issue 8 years ago • 4 comments

Hi,

I'm trying to implement straightforward thing - catch "Unauthorized" error and redirect user to the "/login" page. How do I do that with redux-api?

I assume the way to go is to implement responseHandlerbut it's unclear how to access state from within it.

Any suggestions? Thanks in advance.

divan avatar Jun 03 '17 12:06 divan

I think there is an example of exactly what you're trying to do here: https://github.com/lexich/redux-api/blob/master/docs/AuthorizationJWT.md

jakeaaron avatar Jun 03 '17 17:06 jakeaaron

@divan if you use solutions like redux-router postfetch option can help you for concrete endpoint. if you want to define global interceptor - useresponseHandler

reduxApi({ ... }).use("responseHandler",
  (err, data)=> {
      if (isNeedRedirect(err)) {
        store.dispatch(redirectTo(''));
        // or 
        window.location.href = '.....';
       // or you router api
      }
  });

But you should be careful, because this method catch all requests, and not at all bad responses need to been redirected.

lexich avatar Jun 03 '17 18:06 lexich

@jakeaaron thanks, I've checked this example, but it's not clear. What is check_auth endpoint? Will this request will be happening before each other API request?

If I understood it correctly, I think my approach is slightly different - if any of normal API requests is getting "Unuathorized" error from backend, simply dispatch logout action (which will handle token local storage and router redirection).

@lexich is it a right way to do redirect using window.location? I also currently don't see clearly how do I get access to store and dispatch from within reduxApi(). I'm still new to redux, so maybe it's really obvious, but I can't see anything similar in examples.

And, to be clear, I'm not trying to invent anything on my own. I'm trying to go as "standard" as possible. And I suppose, this functionality is a very basic one.

divan avatar Jun 06 '17 15:06 divan

@divan it depends. If you use react-router, you should use it redirect methods

lexich avatar Jun 06 '17 16:06 lexich