Home > other >  Building React usecontext in typescript got compile issue
Building React usecontext in typescript got compile issue

Time:05-21

So I am trying to build a useAuth context, so after user login to app, then the jwt token can be access from any component later I am facing a strange compile issue never had before, please see screenshot: enter image description here

plain code as below:

    import { createContext, useContext, useReducer } from "react";
import authReducer, { initialTokenValue } from "../reducers/authReducer";

const AuthContext = createContext(initialTokenValue);

export const AuthProvider = ({ children }) => {
  const [state, dispatch] = useReducer(authReducer, initialTokenValue);

  const fetchNewTokenValue = (token: any) => {
    dispatch({
      type: "GET_AUTH_TOKEN",
      payload: token,
    })
  };

  const value = {
    token: state.token,
    fetchNewTokenValue,
  };


  //VS code complain AuthContext as: Cannot find namespace 'AuthContext'.ts(2503)
  //No quick fixes available
  //and Operator '<' cannot be applied to types 'boolean' and 'RegExp'.ts(2365)
  //Unterminated regular expression literal.ts(1161)
  //No quick fixes available
  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}

const useAuth = () => {
  const context = useContext(AuthContext);

  if (context === undefined)  {
    throw new Error("useAuth must be used within AuthContext");
  }

  return context;
}

export default useAuth;

In theroy , it should work, then I can use as below: enter image description here

But as you can see in first screenshot, I cannot find a way to get rid of the redline. And the app is not running because of the errors. Very strange.. it should work, right? Can anyone point me out what's wrong with the setup ? Thanks

CodePudding user response:

Your filename should end with .tsx instead of .ts when using JSX (html in js)

CodePudding user response:

type AuthProviderProps {
    chidren: JSX.Element
};

const AuthProvider = ({children}: AuthProviderProps) => {}

May be you can first resolve the type error on props like this and try out

  • Related