I am refactoring to TypeScript a tutorial in ReactJS that I am following. For the most part, the tutorial teaches you how to refactor most of the code as bonus material. However the log-in part is done in ReactJS/JavaScript only and I tried to refactor my code as a way to challenge myself. The part I am stuck on is createContext as I am not able to understand the types needed.
Original JS code
JS code - Context/Provider
import React, { useState, createContext } from "react";
export const Context = createContext();
const UserProvider = ({ children }) => {
const [state, setState] = useState(undefined);
return (
<Context.Provider value={[state, setState]}>{children}</Context.Provider>
)
};
export default UserProvider;
On the Login component it gets called with const [_user, setUser] = useContext(Context);
My attempt
What I've tried
I tried to apply the following solutions and I'm not really grasping the concepts well enough to apply them successfully:
- Cannot declare React context in typescript? [duplicate]
- Cannot find namespace 'ctx' error when creating Context with react - typescript
- How to use React Context with TypeScript
- React Context + TypeScript — The Easy Way
TS code - Context/Provider
import React, { useState, createContext } from "react";
import { IUser, UserContextType } from "./@types/context";
export const Context = createContext<UserContextType | undefined>(undefined);
const UserProvider: React.FC<React.ReactNode> = ({ children }) => {
const [state, setState] = useState<IUser>();
return (
<Context.Provider value={{state, setState}}>{children}</Context.Provider>
)
};
export default UserProvider;
TS code - types
export interface IUser {
user: string;
password: string;
};
export type UserContextType = {
state: IUser;
setState: (newSession: IUser) => void;
};
Errors
<Context.Provider value={{state, setState}}>{children}</Context.Provider>
Type 'IUser | undefined' is not assignable to type 'IUser'. Type 'undefined' is not assignable to type 'IUser'.ts(2322)
const [_user, setUser] = useContext(Context);
Type 'UserContextType | undefined' is not an array type.ts(2461)
stateorsetStatein its type. Did you mean to use those names instead ofsessionsandsaveSession? Also, since you're passing in an object as the context value, the return value ofuseContextwill also be an object (with those properties), not an array (so don't use[]brackets)TS code - Context/ProviderandErrorscode snippets. I suggest you using what is inTS code - Context/Providervalue={[state, setState]}Decide on either an array or an object, then use that schema everywhere