lexich/redux-api

[Question] how to change state in responseHandler?

divan opened this issue · 4 comments

divan commented

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.

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

@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.

divan commented

@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 it depends. If you use react-router, you should use it redirect methods