I am trying to create a custom hook using ts that will be returning a function living inside it, the way I try to do it is:
export const useHook = () => {
const function1 = () => {
logic here
};
const function2=()=>{
logic here
}
return [function1,function2];
};
then i try to use it in a component like this:
import { useHook } from "./connector/useHook";
function App() {
const {function1,function2} = useHook();
return (
<div>
<Home />
<button onClick={() => function1}>test</button>
<button onClick={() => function2}>test</button>
</div>
);
}
export default App;
however i get an error saying that
Property 'connectWallet' does not exist on type '(() => void)[]'.
const { function1, function2 } = useHook();
CodePudding user response:
replace {}
with []
since you are returning it as an array:
const [function1, function2] = useHook();
or return an object from your hook:
export const useHook = () => {
const function1 = () => {
// logic here
};
const function2 = () => {
// logic here
};
return {function1, function2};
};
then you can use it as:
cosnt {function1, function2} = useHook();
CodePudding user response:
You have returned your functions as the array return [function1,function2];
. While you are using like const {function1,function2} = useHook();
So there are two approaches you can use
Approach 1:
Return your functions as an object from custom hook:
return { function1, function2 };
And use it like
const { function1, function2 } = useHook();
Approach 2:
Return your functions as an array from custom hook:
return [function1, function2];
And use it like
const [function1, function2] = useHook();