Home > Enterprise >  React - Run a function on useEffect and on element click?
React - Run a function on useEffect and on element click?

Time:05-16

I have a funtion inside a useEffect hook that requests some data to my server:

useEffect(() => {
  const reqFn = async () => {
    // req code...
    setState(req result)
  }
  return reqfn()
},[setState])

Also, I need to run this function when a user clicks on a button to request a different data (reqFn uses a useState value as a prop for the server request).

I've tried taking the reqFn() outside the useEffect, but this makes running reqFn in a loop. How can I achieve this?

CodePudding user response:

As I see from your question you need api data in the first render and then you are handling updates with just click. So you can use useEffect without state callback and handle the rest with onClick

const reqFn = async () => {
    // req code...
    setState(req result)
}

useEffect(() => {
  reqfn()
},[])

<>
...
//Rest of your component
<button onClick={reqFn}>Click</button>
...
</>
  • Related