Home > Net >  How to React Context api typescript setting?
How to React Context api typescript setting?

Time:12-31

I am changing the app.js file to app.tsx.

Currently, the value has the following error.

app.tsx

import React, { createContext, useState } from "react";
import SelectPage from "./pages/select/select";
import ResultPage from "./pages/result/result";
import { Route, Routes } from "react-router-dom";

export const GlobalContext = createContext(null);

function App() {
  const [checkCrypto, setCheckCrypto] = useState([]);
  const [start, setStart] = useState(false);

  const value = {
    checkCrypto,
    setCheckCrypto,
    start,
    setStart,
  };

  return (
    <>
      <GlobalContext.Provider value={value}>
        <Routes>
          <Route path="/" element={<SelectPage />} />
          <Route path="/result" element={<ResultPage />} />
        </Routes>
      </GlobalContext.Provider>
    </>
  );
}

export default App;

enter image description here

As I changed it like the code below, it was solved, but I want to find another way.

export const GlobalContext:any = createContext(null);

What type should I apply to solve the problem?

CodePudding user response:

I solved it like this.

interface AppContextInterface {
  checkCrypto: number[];
  start: boolean;
}

export const GlobalContext = createContext<AppContextInterface | null>(null);

function App() {
  const [checkCrypto, setCheckCrypto] = useState([]);
  const [start, setStart] = useState(false);

  const value = {
    checkCrypto,
    setCheckCrypto,
    start,
    setStart,
  };

  return (
    <>
      <GlobalContext.Provider value={value}>
        <Routes>
          <Route path="/" element={<SelectPage />} />
          <Route path="/result" element={<ResultPage />} />
        </Routes>
      </GlobalContext.Provider>
    </>
  );
}

export default App;

CodePudding user response:

Based on the code you've shown, this should work.

If you visit the TypeScript playground link and hover over value on line 14, you can see the type that you need to use as the generic for createContext.

TS Playground

export const GlobalContext = createContext<{
  checkCrypto: number[];
  setCheckCrypto: React.Dispatch<React.SetStateAction<number[]>>;
  start: boolean;
  setStart: React.Dispatch<React.SetStateAction<boolean>>;
}>(undefined as any);

function App() {
  const [checkCrypto, setCheckCrypto] = useState<number[]>([]);
  const [start, setStart] = useState(false);

  const value = {
    checkCrypto,
    setCheckCrypto,
    start,
    setStart,
  };

// ...
  • Related