Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Re-use interceptor across multiple files #41

Open
seanmavley opened this issue Oct 31, 2019 · 2 comments
Open

Re-use interceptor across multiple files #41

seanmavley opened this issue Oct 31, 2019 · 2 comments

Comments

@seanmavley
Copy link

I currently have this in my auth.tsx file, and it works fine


import fetchIntercept from 'fetch-intercept';

export default fetchIntercept.register({
  request: function (url, config) {
    // Modify the url or config here
    config.headers.append = {
      'content-type': 'application/json',
      'Authorization': 'my authorization'
    }
    return [url, config];
  },

  requestError: function (error) {
    // Called when an error occured during another 'request' interceptor call
    return Promise.reject(error);
  },

  response: function (response) {
    // Modify the reponse object
    return response;
  },

  responseError: function (error) {
    // Handle an fetch error
    return Promise.reject(error);
  }
});

export function login(username: string, password: string) {
  // ${process.env.REACT_APP_API_BASE}/api/v1/users/login/
  return fetch('http://localhost:8000/api/v1/users/login/', {
    method: 'POST',
    body: JSON.stringify({ 'username': username, 'password': password })
  })
}

Let's say I have books.service.tsx file, and I wanna make use of the already defined interceptor from the auth.tsx in there. How do I go about it?

@emmanuel-D
Copy link

emmanuel-D commented Oct 31, 2019

I am facing the same issue using React Native.
I also want to use this interceptor globally in my App so that I only instantiate it one time at the app-bootstrap.

@seanmavley are you also using React Native? If yes, then which fetch-library are you using to make your requests?

@gucki
Copy link

gucki commented Jun 21, 2022

How did you solve it? I faced the same issue (different errors when importing it in multiple files), so I just did a "window.fetchIntercept = fetchIntercept" where I import it and then use "window.fetchIntercept" everywhere. Works without any issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants