'Problem with Context API on react With TypeScript to export functions
I've created a API context in this way:
import { createContext, ReactNode, useState } from "react";
interface ProvidersProps { children: ReactNode; }
export const CounterContext = createContext(0);
export const CounterProvider = ({ children }: ProvidersProps) => { let [counter, setCounter] = useState(0);
const plusOne = () => {
setCounter(counter + 1); }
const minusOne = () => {
setCounter(counter - 1); };
return (
<CounterContext.Provider value={{ plusOne, setCounter, minusOne }}>
{children}
</CounterContext.Provider> ); };
And i just trying to use the plusOne and minusOne function in other component, but i getting an error that says:
"Property 'plusOne' does not exist on type 'number'."
const counter = useContext(CounterContext);
return (
<main>
<CounterContext.Provider value={{ count, setCount }}>
<button
onClick={() => {
counter.plusOne()
}}
>
test button
</button> </main>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
