TS2322: Type '{ userName: string; setUserName: React.Dispatch<React.SetStateAction<string>>; }' is not assignable to type 'string'

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>

  )
}

>Solution :

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.

Leave a Reply