Typescript variable being used before assigned

早过忘川 提交于 2020-02-25 05:41:26

问题


As per instructions followed here, I'm trying to cache my endpoint URL and token from Auth0 before constructing my Apollo client:

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;

I'm getting the error TS2454 (variable is used before being assigned) for both endpoint and token above. Any idea how I can get around this?


回答1:


You're declaring both endpoint and token as variables, but not initializing them to anything before checking them inside of 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 };
    });

Try setting default values:

let endpoint: string = "";
let token: string = "";


来源:https://stackoverflow.com/questions/60100960/typescript-variable-being-used-before-assigned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!