Doubt about how "import" works

Asked

Viewed 42 times

0

I am learning JS and Reactnative and for that I am studying about the creation of a backend in Node.js and a frontend in React Native and one thing caught my attention.

In my backend when the user is successfully authenticated is sent as a reply a JSON containing the name, email and JWT token.

In my frontend I receive such information and include the token in the AXIOS header to be used in future requests, example:

Auth.js

import axios from 'axios'

export default class Auth extends Component {
   signin = async () => {
        try {
            const res = await axios.post(`${server}/signin`, {
                email: this.state.email,
                password: this.state.password
            })

            AsyncStorage.setItem('userData', JSON.stringify(res.data))
            axios.defaults.headers.common['Authorization'] = `bearer ${res.data.token}`
            this.props.navigation.navigate('Home', res.data)
        } catch (e) {
            showError(e)
        }
    }
}

Well, as you can see I include the token with the command:

axios.defaults.headers.common['Authorization'] = `bearer ${res.data.token}`

So far so good, what struck me is that in other modules I can "enjoy" this token that was added in the header in the module Auth.js. For example:

Tasklist.js

import axios from 'axios'
export default class TaskList extends Component {
deleteTask = async taskId => {
        try {
            await axios.delete(`${server}/tasks/${taskId}`)
            this.loadTasks()
        } catch (e) {
            showError(e)
        }
    }
}

I’m a layman, but it seems that when I import Aces into Tasklist.js, it sees everything I’ve done in Auth.js Moves, including the added token. Is that how import works? Would you have some text on the subject for me to devour?

Until then I imagined import as for example a constant, for example const Xios, so what I did in one module would not reflect in another.

Thank you for your attention

  • 1

    axios.defaults.headers You had the token placed as a standard header...

  • @bfavaretto what he did would be a Singleton? The correct, perhaps, would be to pass these values in the constructor or in the function.

  • 2

    @Cmtecardeal, in fact it is only one object. As the object is not recreated at each import, the reference is always the same, which allows this type of "modification", which persists to all future importers. In the case of this caching is exposed by Commonjs; in ESM, although it exists, it is private.

  • 2

    Just as a function declared es6 modules has its own context. What happens is that qnd you import a file with existing context the same is saved. The article I have that explains this better is in English https://krasimirtsonev.com/blog/article/javascript-module-system-for-state-management

No answers

Browser other questions tagged

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