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 = {
sessions: IUser[];
saveSession: (newSession: IUser[]) => void;
};
Errors
<Context.Provider value={{state, setState}}>{children}</Context.Provider>
Type ‘{ state: IUser[]; setState: React.Dispatch<React.SetStateAction<IUser[]>>; }’ is not assignable to type ‘UserContextType’. Object literal may only specify known properties, and ‘state’ does not exist in type ‘UserContextType’.ts(2322)
const [_user, setUser] = useContext(Context);
Type ‘UserContextType | undefined’ is not an array type.ts(2461)