Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 }
}

>Solution :

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" },
    });
  };
};

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading