[英]React-native: avoid making every authenticated remote call async
我有一个反应本机项目,它依赖于在对我的后端进行经过身份验证的调用时从 SecureStorage 获取凭据。 与正常的反应不同,这是一个异步过程,这意味着每次我需要标题时我都必须处理 promise。 由于我每次都需要阻止获取凭据,但不应该/不能强制 async 同步,这意味着很多不必要的代码(链接“thens”或进行远程调用 async/await)。 有没有更优雅的方式来处理这种情况?
我能想到的两个选项是 1.) 每次都处理 promises 或 2.) 传入具有全局上下文的 auth 标头。
这是我所拥有的一个例子
useFeedFetch = (payload: GetItemsRequest) => {
// misc state set here
useEffect(() => {
const getFeedAsync = async () => {
// gets credentials from secure storage
let headers = await AuthService.getAuthHeader()
axios({
method: 'POST',
url: requestUrl,
headers: headers,
data: payload,
}).then((res) => {
...
}
}
getFeedAsync()
}
, [payload.page]);
return {
loading, error, items, hasMore,
};
您当然可以使用Axios 拦截器使其更不可见
// eg api.js
import axios from "axios"
import AuthService from "wherever"
// create a new instance to include your interceptor
export const api = axios.create({
// baseURL can be handy to shorten your URLs
})
api.interceptors.request.use(async config => ({
...config,
headers: {
...config.headers,
...await AuthService.getAuthHeader()
}
}))
现在您可以使用api
代替axios
,它会在每个请求上自动应用您的身份验证标头
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.