简体   繁体   English

React - Mobx - Fetch - DRY 最佳实践

[英]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 .为了简单起见,假设我有 3 个 mobx 商店PeopleStorePlacesStoreAuthStore

All of these stores connect to a 3rd party api using fetch .所有这些商店都使用fetch连接到第 3 方 api。

The AuthStore provides login functionality and has a property: @observable apiToken AuthStore提供登录功能并有一个属性: @observable apiToken

There is duplicate logic in the other stores, setting the api url, the token, etc...其他商店有重复逻辑,设置api url,token等...

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然后在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?这是一个好方法还是有更好的方法来 go 关于这个?

  • How do I access the apiToken inside api.js ?如何访问apiToken中的api.js

  • Am I correct in assuming that api is just a function and not a react component?我是否正确假设api只是 function 而不是反应组件?

    • If so, can I still inject the AuthStore into the api() ?如果是这样,我仍然可以将AuthStore inject 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?我的另一个想法是将所有商店包装在提供此功能的HOC中,但同样(我假设)商店不是实际的反应组件,这会导致任何问题吗?

Another approach would be to just set your authorization header globally at the top level of your app.另一种方法是在应用程序的顶层全局设置您的授权 header 。 This would require you to install axios or something similar这将需要您安装axios或类似的东西

For example, in your root index.js:例如,在您的根 index.js 中:

  • Get your api key, via process.env.apiToken or however you are getting it获取您的 api 密钥,通过process.env.apiToken或者您正在获取它
  • Set the header:设置 header:

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

You can also set the base URL to help with the paths:您还可以设置基本 URL 以帮助路径:

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.这样您就不必担心令牌,它只会被照顾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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