简体   繁体   中英

Invoke React custom hook on form submit

I have created a custom useFetch hook in order to make an API request in a few different areas within the application. One instance it is being used is when a component is being rendered, and therefore it works as intended. However I have another place where the request is to be made when the user submits the form. I am encountering an error stating "Expected an assignment or function call and instead saw an expression" at the line where it shows {data} inside handleSubmit

App.js:

import { useFetch } from "./components/useFetch";

function App() {
  const [value, setValue] = useState([]);
  const {data} = useFetch("search", value);

  const handleChange = event => {
    setValue(event.target.value);
  };

  const handleSubmit = event => {
    event.preventDefault();
    setData("search", value);
  };

  return (
    <Form onSubmit={handleSubmit}>
       <Form.Group>
           <InputGroup className="mb-3">
               <FormControl value={value} onChange={handleChange} placeholder="Search" aria-label="Search" aria-describedby="basic-addon2" />
                  <InputGroup.Append>
                    <Button type="submit" variant="primary">Search</Button>
                  </InputGroup.Append>
                </InputGroup>
              </Form.Group>
            </Form>
    {data.map(data => (
      <p>{data.description}</p>
    ))}
  );
}

useFetch.js:

import { useState, useEffect } from 'react';

export const useFetch = (endpoint, value) => {

  const [isLoaded, setIsLoaded] = useState(false);
  const [error, setError] = useState(null);
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(`http://127.0.0.1:8443/${endpoint}/${value}/?key=key`, {
        mode: 'cors',
        credentials: 'include'
      })
        .then(res => res.json())
        .then(
          (json) => {
            setIsLoaded(true);
            setData(json.result);
          },
          (error) => {
            setIsLoaded(true);
            setError(error);
          }
        )
    };
    fetchData();
  }, [endpoint, value]);

  return {data};

};

Well

 const handleSubmit = event => {
    event.preventDefault();
    {data} //this is not a function call this is an obj definition without assignement so is just an error
  };

if you need to triggere again your hook, you can change data or add a trigger function so, in your hook:

const doStuff =   async () => {
  const response = await fetch(`http://127.0.0.1:8443/${endpoint}/${value}/?key=key`, {
    mode: 'cors',
    credentials: 'include'
  })
    .then(res => res.json())
    .then(
      (json) => {
        setIsLoaded(true);
        setData(json.result);
      },
      (error) => {
        setIsLoaded(true);
        setError(error);
      }
    )
};
}


 useEffect(doStuff, [endpoint, value]);


  return {data, doStuff};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM