Home > other >  TS2322: Type '{ userName: string; setUserName: React.Dispatch<React.SetStateAction<string
TS2322: Type '{ userName: string; setUserName: React.Dispatch<React.SetStateAction<string

Time:09-27

I'm trying to use ReactContext for global state management. I have copied the code from this example: https://codesandbox.io/s/update-context-value-l39t0?file=/src/App.js

Yet typescript is throwing the following error: TS2322: Type '{ userName: string; setUserName: React.Dispatch<React.SetStateAction<string>>; }' is not assignable to type 'string'.

Attached is my code:

const UserContext = createContext('Unknown');

export default function App() {
  const [accessibilityMode, setAccessibilityMode] = useState<string>("");
  const [userName, setUserName] = useState<string>("");

  const value = useMemo(
    () => ({ userName, setUserName }),
    [userName]
  );

  return(
    <BrowserRouter>
      <div className={accessibilityMode}>
        <UserContext.Provider value={value}>
        <NavBar setAccessibilityMode={setAccessibilityMode}/>
        <div className="webpage-content">
        <Routes>
          <Route path="" element={<Home/>}/>
          <Route path="/resources" element={<Resources/>}/>
          <Route path="/contact" element={<ContactUs/>}/>
          <Route path="/projects" element={<Projects/>}/>
          <Route path="/fnssa" element={<WhatIsFNSSA/>}/>
          <Route path="/statement" element={<Statement/>}/>
          <Route path="/minutes" element={<MeetingMinutes/>}/>
          <Route path="/team" element={<OurTeam/>}/>
        </Routes>
        </div>
        </UserContext.Provider>
      </div>
    </BrowserRouter>

  )
}

CodePudding user response:

Typescript is inferring the type from creatContext('unknown'), unknown is a string and so it's inferring that the value given to the context would be string.

Change the createContext call to be

const UserContext = createContext<{
    userName: string;
    setUserName: React.Dispatch<React.SetStateAction<string>>;
}>({
    userName: "",
    setUserName: () => {},
});

// rest of your component

It should work.

CodePudding user response:

It's because you're setting the initial value of the context as const UserContext = createContext('Unknown');. Typescript infers the type as a string.

Use this instead:

interface UserContextType {
    userName: string; 
    setUserName: React.Dispatch<React.SetStateAction<string>>;
}
const UserContext = createContext<UserContextType>({} as UserContextType);

  • Related