简体   繁体   中英

Using Custom hooks in React the right way

I have been having major problems understanding the best approach to using/calling my custom hooks inside a function. in my resent code, I am trying to call a custom fetch hook in my app.js

I want to send the following properties (name and age) to my server to handle database storage there, so i intend to have this action happen when the user clicks a button after filling in their name and age. code below

app.js

const [name, setName] = useState('Owen');
const [age, setAge] = useState(22);

const handleClick = () => {
//if statement to check that name and age where provided
  const {data,error} = useFetchPost('url',{name:name,age:age}); 
}

useFetchPost.js

const useFetchPost = ({url, val}) => {
 
 const [data, setData] = useState(null);
 const [error, setError] = useState(null);

 useEffect(()=> {
  fetch(url,{method:'POST',header: {'Content-Type': 'application/json'}, 
  body:JSON.stringify(val)})
  .then(res =>  return res.json())
  .then(data => setData(data))
  .catch(err => setError(err))
 }, [url, val])

 return { data, error }
}

Hooks need to be called when the component renders, not when a click happens. But you can have your hook return a function, and then call that function in handleClick. For example:

const useFetchPost = () => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  const doFetch = useCallback((url, val) => {
    fetch(url, {
      method: "POST",
      header: { "Content-Type": "application/json" },
      body: JSON.stringify(val),
    })
      .then((res) => res.json())
      .then((data) => setData(data))
      .catch((err) => setError(err));
  }, []);

  return { data, error, doFetch };
};

// used like:
const App = () => {
  const { data, error, doFetch } = useFetchPost();

  const handleClick = () => {
    doFetch(url, {
      method: "POST",
      header: { "Content-Type": "application/json" },
    });
  };
};

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