admin管理员组文章数量:1287598
I am trying to use context in NextJS with Typescript. One of the values in my context is a useState setter function. Setting the default value of that in the createContext arguments is giving me this error.
Property 'Dispatch' does not exist on type 'typeof import("d:/NextJS/crypto-tracker/node_modules/@types/react/index.d.ts")'
I am getting the same error for SetStateAction if I remove Dispatch. The following is the code in my context file.
"use client";
import React, { createContext, useEffect, useState, Dispatch } from "react";
export const CryptoContext = createContext({
allCoins: [],
currency: { name: "usd", symbol: "$" },
setCurrency: React.Dispatch<
React.SetStateAction<{ name: "usd"; symbol: "$" }>
>,
});
const CryptoContextProvider = ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
const [allCoins, setAllCoins] = useState([]);
const [currency, setCurrency] = useState({ name: "usd", symbol: "$" });
const fetchAllCoins = async () => {
const options = {
method: "GET",
headers: {
accept: "application/json",
"x-cg-demo-api-key": "",
},
};
fetch(
`=${currency.name}`,
options
)
.then((res) => res.json())
.then((res) => setAllCoins(res))
.catch((err) => console.error(err));
};
useEffect(() => {
fetchAllCoins();
}, [currency]);
const contextValue = { allCoins, currency, setCurrency };
return (
<CryptoContext.Provider value={contextValue}>
{children}
</CryptoContext.Provider>
);
};
export default CryptoContextProvider;
package.json
{
"name": "crypto-tracker",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "15.1.7",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@types/node": "^20",
"@types/react": "^19.0.10",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "15.1.7",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"typescript": "^5"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
I have tried reinstalling react, @types/react and react-dom. I have also tried switching the Typescript version to use workspace version but it shows both workspace version and VS Code version as 5.7.3. The error is still present.
I am trying to use context in NextJS with Typescript. One of the values in my context is a useState setter function. Setting the default value of that in the createContext arguments is giving me this error.
Property 'Dispatch' does not exist on type 'typeof import("d:/NextJS/crypto-tracker/node_modules/@types/react/index.d.ts")'
I am getting the same error for SetStateAction if I remove Dispatch. The following is the code in my context file.
"use client";
import React, { createContext, useEffect, useState, Dispatch } from "react";
export const CryptoContext = createContext({
allCoins: [],
currency: { name: "usd", symbol: "$" },
setCurrency: React.Dispatch<
React.SetStateAction<{ name: "usd"; symbol: "$" }>
>,
});
const CryptoContextProvider = ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
const [allCoins, setAllCoins] = useState([]);
const [currency, setCurrency] = useState({ name: "usd", symbol: "$" });
const fetchAllCoins = async () => {
const options = {
method: "GET",
headers: {
accept: "application/json",
"x-cg-demo-api-key": "",
},
};
fetch(
`https://api.coingecko/api/v3/coins/markets?vs_currency=${currency.name}`,
options
)
.then((res) => res.json())
.then((res) => setAllCoins(res))
.catch((err) => console.error(err));
};
useEffect(() => {
fetchAllCoins();
}, [currency]);
const contextValue = { allCoins, currency, setCurrency };
return (
<CryptoContext.Provider value={contextValue}>
{children}
</CryptoContext.Provider>
);
};
export default CryptoContextProvider;
package.json
{
"name": "crypto-tracker",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "15.1.7",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@types/node": "^20",
"@types/react": "^19.0.10",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "15.1.7",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"typescript": "^5"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
I have tried reinstalling react, @types/react and react-dom. I have also tried switching the Typescript version to use workspace version but it shows both workspace version and VS Code version as 5.7.3. The error is still present.
Share Improve this question edited Feb 28 at 6:25 Hamed Jimoh 9868 silver badges19 bronze badges asked Feb 24 at 13:27 Swapnodip ChakrabartiSwapnodip Chakrabarti 32 bronze badges1 Answer
Reset to default 0React.Dispatch refers to a type but you are using it as a value in the CryptoContext variable. Here is an improved version of your code using interfaces and initializing the context with a null value.
import React, {
createContext,
useEffect,
useState,
Dispatch,
SetStateAction,
} from "react";
interface Currency {
name: "usd";
symbol: "$";
}
interface CryptoContext {
allCoins: never[]; // improve type here;
currency: Currency;
setCurrency: Dispatch<SetStateAction<Currency>>;
}
export const CryptoContext = createContext<CryptoContext | null>(null);
const CryptoContextProvider = ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
const [allCoins, setAllCoins] = useState([]);
const [currency, setCurrency] = useState<Currency>({
name: "usd",
symbol: "$",
});
const fetchAllCoins = async () => {
const options = {
method: "GET",
headers: {
accept: "application/json",
"x-cg-demo-api-key": "",
},
};
fetch(
`https://api.coingecko/api/v3/coins/markets?vs_currency=${currency.name}`,
options
)
.then((res) => res.json())
.then((res) => setAllCoins(res))
.catch((err) => console.error(err));
};
useEffect(() => {
fetchAllCoins();
}, [currency]);
const contextValue = { allCoins, currency, setCurrency };
return (
<CryptoContext.Provider value={contextValue}>
{children}
</CryptoContext.Provider>
);
};
export default CryptoContextProvider;
本文标签:
版权声明:本文标题:reactjs - Property 'Dispatch' does not exist on type 'typeof import("d:NextJScrypto-trackernode 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741267337a2368724.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论