im having this issue since i moved the code from React Javascript to React Typescript
I have this simple hook that switch state from on/off (or true false) (code below) I'm struggling into this since this code were working on Javascript
Code here to test it
So the toggle function has some error but cannot figure it out. Some help would be much appreciated
// useToggle.tsx
import { useState } from "react";
export const useToggle = (initialMode = false) => {
const [open, setOpen] = useState(initialMode);
const toggle = () => setOpen(!open);
return [open, setOpen, toggle];
};
My switch component
// Switch.tsx
import { useToggle } from "./useToggle";
import React from "react";
export const Switch = () => {
const [open, toggle] = useToggle();
const [open2, toggle2] = useToggle();
return (
<>
<p>Testing toggle 1: {`${open}`}</p>
<p>Testing toggle 2: {`${open2}`}</p>
<button
onClick={() => {
toggle();
}}
>
Toggle 1
</button>
<button
onClick={() => {
toggle2();
}}
>
Toggle 2
</button>
</>
);
};
And now i use my switch component
// App.tsx
import * as React from "react";
import "./styles.css";
import { Switch } from "./Switch";
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Switch />
</div>
);
}
Two changes you need to do to solve the problem
First, to get rid of the error you need to return the value with const assertion
like
return [open, toggle, setOpen] as const;
Here is a Link to github issue for the error
and secondly you are using toggle as the second argument while destructing, so you need to return it as the second argument too
Working DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With