Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Typescript hook error - This expression is not callable

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

enter image description here

// 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>
  );
}
like image 834
Héctor León Avatar asked May 01 '20 13:05

Héctor León


1 Answers

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

like image 184
Shubham Khatri Avatar answered Nov 06 '22 07:11

Shubham Khatri