Akash Bhandwalkar Akash Bhandwalkar - 1 month ago 30
React JSX Question

How to write interceptor in react-redux?

I have to pass token, received from server, after login to every api. so my question is how to write an interceptor which will append token on every api call. I am using 'request-promise' to call api.

Thanks!

Answer

I would create a wrapper (interface) function for your 'request-promise' calls:

export default class RequestInterface {
    constructor(accessToken) {
        this.accessToken = accessToken;
    }

    request({
        method,
        uri,
        body,
    }) {
        return rp({
            method,
            uri,
            body,
            qs: {
                access_token: this.accessToken,
            },
        });
    }
}

This way on every RequestInterface.request() call, you'll have your credentials there.

(I didn't test this but that's the basic idea)