gpt4 book ai didi

single-page-application - 在分配之前使用的 typescript 变量

转载 作者:行者123 更新时间:2023-12-04 10:37:21 25 4
gpt4 key购买 nike

按照说明遵循 here ,我试图在构建我的 Apollo 客户端之前缓存我的端点 URL 和来自 Auth0 的 token :

import React from 'react';
import { ApolloClient, ApolloProvider, from, HttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/link-context';
import { useAuth0 } from './auth/AuthContext';

const App: React.FC = () => {
const { isLoading, getTokenSilently, getIdTokenClaims } = useAuth0();

if (isLoading) return <Loader />;

let endpoint: string;
let token: string;
const contextLink = setContext(async () => {
if (!token) {
token = await getTokenSilently();
}
if (!endpoint) {
endpoint = await getIdTokenClaims()['https://example.com/graphql_endpoint'];
}

return { endpoint, token };
});

/**
* TODO: check for autorization error and remove token from cache
* See: https://www.apollographql.com/docs/react/v3.0-beta/api/link/apollo-link-context/
*/

const apolloClient = new ApolloClient({
cache: new InMemoryCache(),
link: from([
contextLink,
new HttpLink({
uri: endpoint || '',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
}
})
])
});

return (
<ApolloProvider client={apolloClient}>
<div />
</ApolloProvider>
);
};

export default App;


我收到了 endpoint 的错误 TS2454(在分配之前使用了变量)和 token以上。知道如何解决这个问题吗?

最佳答案

您同时声明 endpointtoken作为变量,但在 setContext 中检查它们之前不要将它们初始化为任何东西。

    let endpoint: string;
let token: string;
const contextLink = setContext(async () => {
if (!token) {
token = await getTokenSilently();
}
if (!endpoint) {
endpoint = await getIdTokenClaims()['https://example.com/graphql_endpoint'];
}

return { endpoint, token };
});

尝试设置默认值:
let endpoint: string = "";
let token: string = "";

关于single-page-application - 在分配之前使用的 typescript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60100960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com