简体   繁体   中英

How can i use custom hooks inside my function?

I tried to use my hook inside a function but it doesn't work, so now i tried to send a callback function to reset the hook params but it is still not working.

How can i make this custom hook work in my case?

const del = useFetch(null);
  const handleDelete = id => {
    del.setParams({
       hookUrl: "https://localhost:44354/api/car/" + id, 
       hookOptions: {}
    });

    console.log(del.response);
  };

The hook works fine for GETS cause i dont have any other behavior i want to do, but for the delete i need to pop a modal for example, i know i can use the fetch directly but just curious.

import React from "react";

const useFetch = (url, options) => {
  debugger;
  const [params, setParams] = React.useState({
    hookUrl: url,
    hookOptions: options
  });
  const [response, setResponse] = React.useState(null);
  const [error, setError] = React.useState(null);
  React.useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await fetch(params.hookUrl, params.hookOptions);
        const json = await res.json();
        setResponse(json);
      } catch (error) {
        setError(error);
      }
    };
    fetchData();
  }, []);
  return { setParams, response, error };
};
export default useFetch;
  1. You cannot use a hook inside a function.
  2. You are using the setParams (setState in a wrong way):
const handleDelete = id => {
    del.setParams({
       hookUrl: "https://localhost:44354/api/car/" + id, 
       hookOptions: {}
    });
    console.log(del.response);
  };

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