Home > other >  How to document which Context Provider is being used when calling useContext?
How to document which Context Provider is being used when calling useContext?

Time:11-16

I made a component that renders AuthContext.Provider with certain values.

enter image description here

It works, but when I call useContext in a child of the AuthProvider component, VS Code can't tell the return type of useContext. Is there a way (i.e. with jsdoc comments) for me to document which Provider is being used so VS Code will show the correct type for x?

What I see:

enter image description here

What I want to see:

const x: {
    login: (username: any, password: any) => Promise<void>;
    logout: () => Promise<void>;
}

NOTE: I'd rather not hard-code all the value types in a jsdoc comment if they could be deduced from the Provider. Also, I'm not using Typescript.

CodePudding user response:

Type your AuthContext as a Context<Type> object:

/**
 * Whatever your context object type.
 * @typedef ICTXDefault
 */

/**
 * @type {ICTXDefault}
 */
const defaultContext = {};

/**
 * @type {import("react").Context<ICTXDefault>}
 * 
const AuthContext = createContext(defaultContext);
  • Related