What is the problem with below code? I got warning by typescript when use useState
import * as React, { useState } from 'react'
const useForm = (callback: any | undefined) => {
const [inputs, setInputs] = useState({}) //error: Cannot find name 'useState'.ts(2304)
const handleInputChange = event => {
event.persist()
setInputs(inputs => ({
...inputs,
[event.target.name]: event.target.value,
}))
}
return {
handleInputChange,
inputs,
}
}
export default useForm
What is the problem with below code? I got warning by typescript when use useState
import * as React, { useState } from 'react'
const useForm = (callback: any | undefined) => {
const [inputs, setInputs] = useState({}) //error: Cannot find name 'useState'.ts(2304)
const handleInputChange = event => {
event.persist()
setInputs(inputs => ({
...inputs,
[event.target.name]: event.target.value,
}))
}
return {
handleInputChange,
inputs,
}
}
export default useForm
https://codesandbox.io/s/react-typescript-starter-lmub8
Share Improve this question edited Sep 27, 2020 at 10:18 falinsky 7,4284 gold badges34 silver badges58 bronze badges asked Mar 19, 2020 at 10:12 JenniferJennifer 3432 gold badges3 silver badges12 bronze badges3 Answers
Reset to default 12Your import statement is invalid.
You can either import everything as React
like this:
import * as React from 'react';
and the access useState
from the React
object:
const [inputs, setInputs] = React.useState({})
or import React
as the default and only partially import other names:
import React, { useState } from 'react'
And the use useState
as before:
const [inputs, setInputs] = useState({});
Try this in formHook.tsx
import React, { useState } from 'react';
and this in app.tsx
import React, { Component } from 'react'
const { inputs, handleInputChange } = useForm;
you can first use React.useState
or import it as individual export. second, you should also specify the event object such as change event or form event.
import * as React from 'react'
import {useState} from 'react';
const useForm = (callback: () => void) => {
const [inputs, setInputs] = useState({});
const handleInputChange = (event:React.ChangeEvent<HTMLInputElement>) => {
event.persist()
setInputs(inputs => ({
...inputs,
[event.target.name]: event.target.value,
}))
}
return {
handleInputChange,
inputs,
}
}
export default useForm