Getting network request each time I pass value in input

Viewed 32

I got a form with simple input, if I will pass wrong value I will get an error ( just like I want to ) then each time I pass a letter It will get a request from the server which I don't want to. this happens only after you submit the form.

  const [product, setProduct] = useState('');
  const [errors, setErrors] = useState('');
  const [productId, setProductId] = useState('');

  const [getProduct, { loading, error }] = useLazyQuery(GET_PRODUCT_BY_ID, {
    variables: { productId },
    onCompleted({ getProductById }) {
      setProduct(getProductById);
      setErrors('');
    },
  });

  const onChange = (e) => {
    setProductId(e.target.value);
  };

  const onSearchSubmit = (e) => {
    e.preventDefault();
    getProduct();
  };

Form -

 <Form onSubmit={onSearchSubmit}>
              <Title>Please type the ID of the item</Title>
              <FormRow
                name='productId'
                type='text'
                value={productId}
                onChange={onChange}
              />
              <Button type='submit'>Search</Button>
              {errors ? (
                <MuiError type='error'>{errors}</MuiError>
              ) : error ? (
                <MuiError type='error'>{error.message}</MuiError>
              ) : (
                ''
              )}
            </Form>

UseLazyQuery is getting calle after every change I put in my input. How can I prevent that from happen? I don't understand why this is happen because getProduct function need to be called only when I submit, not when I am changing values..

0 Answers
Related