Home > Software engineering >  Destructuring react hook results in: This expression is not callable
Destructuring react hook results in: This expression is not callable

Time:09-19

I'm creating a custom hook and want to return an object and two functions when the hook is called. I do not want to return it as return {body, setProperty, setBody}, since I might call the hook multiple times within the same component and need different names for the variables.

I'd want to call it just as useState where I can destructure it as an array const [firstBody, setFirstBodyProp, setFirstBody] = useJSONState({/*Some code*/}), but when I try to return it as such return [body, setProperty, setBody], I get the following error when calling it from a component: This expression is not callable. Type 'jsonType' has no call signatures.ts(2349)

My Code:

type jsonType = {
  [property: string]: any
}

const useJSONState = (json: jsonType) => {

  const [ body, setBody ] = useState(json)

  function setProp(property: string, value: any){
    let newBody = {...body}
    newBody[property] = value
    setBody(newBody)
  }

  return [body, setProp, setBody]
}

export default useJSONState

CodePudding user response:

If you want to return an array of jsonType you should defined the type of the function parameter and set the return type to:

const useJSONState = (func: () => void): jsonType[] => { ... };

CodePudding user response:

The reason for the error is TypeScript inference. Your hook is returning an array of body,setProp,setBody but TypeScript infers the type to be jsonType[], which is the type of body(the first element in the array). To solve this error, you have to specify the return type of the hook explicitly.

export const useJSONState = (
   json: jsonType
): [
   jsonType,
   (property: string, value: any) => void,
   React.Dispatch<React.SetStateAction<jsonType>>
] => {
   // .....
   return [body, setProp, setBody];
}
  • Related