ask4you
ask4you

Reputation: 808

React - Run a function on useEffect and on element click?

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?

Upvotes: 0

Views: 4496

Answers (1)

Evren
Evren

Reputation: 4410

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>
...
</>

Upvotes: 3

Related Questions