Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading