0
votes

I want to delete model's value when manufacturerWatchValue changes after form is initialized.

But model loses its value upon form-initialized since initialized variable is in the dependency list. Hence, I had to remove it from the dependency list to make it work.

Even though it works as expected, React says Line 138:5: React Hook useEffect has a missing dependency: 'initialized'. Either include it or remove the dependency array

Is there a way to bypass this error while achieving the logic?

const MyForm = ({ itemId }) => {
    const { watch, setValue, handleSubmit, reset } = useForm()
    const [initialized, setInitialized] = useState(false)
    const manufacturerWatchValue = watch("manufacturer")

    useEffect(() => {
        // Initializing Form Here
        itemId &&
            (async () => {
                const oneItem = await getOneResult(itemId)
                reset(oneItem)
                setInitialized(true)
            })()

        // Terminating Form Here
        return () => {
            reset({})
            setInitialized(false)
        }
    }, [dispatch, reset, itemId])

    useEffect(() => {
        if (initialized) {
            setValue("model", "")
        }
    }, [manufacturerWatchValue, setValue /*, initialized */])

    const onSubmit = (data) => {
      console.log(data)
    }

    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <input type="text" name="model" ref={register} />
            <input type="text" name="manufacturer" ref={register} />
        </form>
    )
1
Is it even possible to change manufacturerWatchValue when initialized is false? - Ɓukasz Karczewski
no, the value only changes after initialize. - Jake Jeon

1 Answers

1
votes

React is not actually throwing an error at you, instead throwing an eslint warning at you.

You can ignore the specific linting error by adding this line above the dependency error:

// eslint-disable-next-line

Example

useEffect(() => {
  console.log("My code")
  
  // eslint-disable-next-line
}, [])