简体   繁体   中英

React - Mobx - Fetch - DRY Best Practices

I am trying to clean up some code to remove redundancy and have some questions around best practices.

To keep it simple lets say I have 3 mobx stores PeopleStore , PlacesStore , and AuthStore .

All of these stores connect to a 3rd party api using fetch .

The AuthStore provides login functionality and has a property: @observable apiToken

There is duplicate logic in the other stores, setting the api url, the token, etc...

I tried creating the following file:

// ./api.js

const url = 'https://example.com'
const options = {
   headers: {
      Authorization: ??? (how do I access AuthStore.apiToken)
   }
}

export const api = (endpoint) => {
  fetch(url + endpoint, options)
}

Then in PeopleStore

import api from './api'

class PeopleStore {
   getPeople() {
     api('/people');
   }
}

(This is just an example of the concept and not the actual code)

My quesions are:

  • Is this a good approach or are there better ways to go about this?

  • How do I access the apiToken inside api.js ?

  • Am I correct in assuming that api is just a function and not a react component?

    • If so, can I still inject the AuthStore into the api() ? (I believe I ran into issues with this)
  • My other thought would be to wrap all of the Stores in an HOC which provides this functionality, but again (I'm assuming) the Stores are not actual react components, does this cause any issues?

Another approach would be to just set your authorization header globally at the top level of your app. This would require you to install axios or something similar

For example, in your root index.js:

  • Get your api key, via process.env.apiToken or however you are getting it
  • Set the header:

axios.defaults.headers.common['Authorization'] = apiToken;

You can also set the base URL to help with the paths:

axios.defaults.baseURL = 'https://api.example.com';

This way you do not need to worry about the token, it will just be taken care of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM