So I have been doodling with react and typescript for a bit.
Initially working with javascript, but now trying to explore typescript.
I had a ok grasp on useContext in js, with simple a simple boolean state.
But I cant figure out what I’m missing in this typescript implementation.
My context code
import React, { createContext, useState } from 'react';
export interface UserStateInterface{
loggedinIn: boolean;
userid: number;
username: string;
}
type StateContextType = {
user: UserStateInterface;
setUser: React.Dispatch<React.SetStateAction<UserStateInterface>>;
};
export const StateContext = createContext<StateContextType>(
null as unknown as StateContextType,
);
type ContextProviderProps = {
children: React.ReactNode;
};
export const ContextProvider = ({ children }: ContextProviderProps) => {
const [user, setUser] = useState({
loggedinIn: false,
userid: 0,
username: "string",
});
return (
<StateContext.Provider value={{user, setUser}}>{children}</StateContext.Provider>
);
};
Where its implemented.
<StateContext.Provider value={{user: {userid:0, username: "", loggedinIn: false}, setUser() }}>
<Header />
<TabNav />
</StateContext.Provider>
Intially I thought, it would take an object of the userstate, but thats wrong. setUser, is also not ok cause its calling a function that returns void. Maybe theres a better, way to solve this, where the state is never null, but I’m sure I’d benefit from fully understanding this.
I have tried pass different values to value prop