Héctor León
Héctor León

Reputation: 2400

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>
  );
}

Upvotes: 20

Views: 16746

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281744

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

Upvotes: 44

Related Questions