React and Typescript : Error creating a context with jwt info

Viewed 40

I'm trying to create a context using Typescript after login with the info I got from the backend. It works fine in Javascript without Typescript, but I can't make it work with Typescript.

Login.tsx:

const { setAuth } = useAuth();

setAuth.({ user, pwd, role, accessToken });

AuthProvider.tsx:

import { createContext, useState } from "react";
import { IUserData, AuthContextType } from "../interfaces/interfaces";

const AuthContext = createContext<AuthContextType>({});

interface props {
    children: JSX.Element | JSX.Element[]
}

export const AuthProvider = ({ children }: props) => {
    const [auth, setAuth] = useState<IUserData>({});

    return (
        <AuthContext.Provider value={{ auth, setAuth }}>
            {children}
        </AuthContext.Provider>
    )
}

export default AuthContext;

useAuth.tsx:

import { useContext, useDebugValue } from "react";
//import AuthContext from "../context/AuthProvider";
import { IUserData } from "../interfaces/interfaces";
import { createContext, useState } from "react";

const AuthContext = createContext<IUserData>({});

// global auth state to use throughout the application globally
const useAuth = () => { 
    const  auth  = useContext(AuthContext);
    useDebugValue(auth, auth => auth?.user ? "Logged In" : "Logged Out")
    return useContext(AuthContext);
}

export default useAuth;

interfaces.tsx:

import { Dispatch, SetStateAction } from "react";

export interface IUserData {
    user?: string
    pwd?: string
    role?: number
    accessToken?: string
    auth?: {user?: string
        pwd?: string
        role?: number
        accessToken?: string}
    setAuth?: Dispatch<SetStateAction<IUserData>>
}

export type AuthContextType = {
    auth?: IUserData;
    setAuth?: (auth: IUserData) => void;
    //updateTodo: (id: number) => void;
  }; 

On another page after login I try to display the information:

    const { auth } = useAuth();
    console.log(auth);
    console.log(auth?.role);

But I get "undefined"...

I think It's my interfaces file and AuthProvider.tsx that aren't correctly code. Do you know how to change it correctly?

0 Answers
Related