4

How to set global default headers in Axios in dependencies that use Axios too?

I'm making a "react component" (public in npm) that depends on Axios but when that component makes an Ajax call, I need that component to keep the Axios config headers of my (parent) project.

*It looks like my "react-component" makes a new instance of Axios instead of using the Axios instance of my (parent) project.

axios.defaults.headers['authKey']='xxxxxx'

*I already use the Axios interceptors in my (parent) project but the Ajax made for my "react component" is never triggered.

Rodrigo Chaclan
  • 103
  • 1
  • 1
  • 8
  • You can create multiple `axios` instance by calling the `create()` method, but for each instance you have to set the interceptors separately. Does this answer your question? – FisNaN Mar 15 '18 at 22:16
  • what i want is to set default headers for all my instances in one place, for the created and the instances will be created – Rodrigo Chaclan Mar 15 '18 at 22:30
  • How about create an object with your header, and then attach this object to all axios instance? `const axiosSetup = {headers: {'authKey': 'xxx'}}; const instance1 = axios.create(axiosSetup), instance2 = axios.create(axiosSetup);` – FisNaN Mar 15 '18 at 22:35
  • what i would expect to not have a diferent instance of axios, instead use the instance of my (parent) Project in the childs component, so when i use the interceptors, or configs of axios (Parent) Project it change also in the childs projects. – Rodrigo Chaclan Mar 16 '18 at 01:04

1 Answers1

0

I think you can pass your headers to your child component by using props and call Ajax requests in that component with that prop or you can just create a json file (maybe constants file) for that and require them in your child component and expect other developers to create their configurations. And I'm pretty sure that you misunderstood the logic behind import statement. When you import a class in ES6 new instance of that class is created MDN Reference: import . What you should search about is singletons, here is an example of issue that is similar to yours singleton object in react native .

suchcodemuchwow
  • 848
  • 2
  • 9
  • 27
  • the problem is that we want to package that "component" and publish in npm, that component implements axios, so we want to set the headers config in the project where the "component" is imported. So what would be the way to package that "component" in order to have that behavior – Rodrigo Chaclan Mar 16 '18 at 01:08