Reactjs - Catch exported constant

Asked

Viewed 225 times

0

I created a component that exports Axios:

import axios from "axios";
const token = 'Z31XC52XC4';

export default axios.create({
    baseURL: 'https://xxxxx.xxxxx.com.br/api/',
    headers: {
        'Accept': 'application/json, text/plain, */*',
        'Access-Origin': 'D',
        'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjIzMDEyOSwiaXNzIjoiaHR0cDovL3dlYi1zZXJ2aWNlcy55ZWFwcHMuY29tLmJyL2FwaS91c2Vycy9sb2dpbiIsImlhdCI6MTU1ODU0OTIxMCwiZXhwIjoxNTU5NzU4ODEwLCJuYmYiOjE1NTg1NDkyMTAsImp0aSI6ImxOeDlJNmpWWnFWU1NaeVIifQ.WfayLZMLfGRUwoH2LfBhDWgX4soiISrGxr7lZDZOYUA',
        'Company-Token': token
    }
});

On the other side I need to pick up this constant called token:

import api from '../src/components/Util/api.js';
const token = api.token; ?????

Could someone tell me how to do this?

1 answer

0

To import something you need to export first:

export const token = 'Z31XC52XC4';

Before showing how to import, it is worth explaining two types of import. The first is the default( which is the one you’re using). To be able to use it you need to have a export default. She’s one of a kind, which means I can’t have two export default in a code. And when importing, you don’t need to put the same name that was declared.

The other export/import is the "common" you export as the example I gave above and import using a key pair{}. In that case, the export name has to be the same as the import name.

In your case it looks like this:

import api, { token } from '../src/components/Util/api.js';

Now you can use the token normally.

Note: As demonstrated using your code, it is possible to have both export types in a single file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.