0

In my reactjs application in which I have a functional component and completed is a state and it is defined as below using hooks.

const [completed, setCompleted] = useState(false)

Question 1:

When component renders for the first time i want to invoke a parameterized function checkEmpty without arguments inside useEffect as below. This checkEmpty function will return a boolean value. But the function below is not getting triggered inside useEffect. I want to make the code to invoke checkEmpty function and if it returns true the completed state should set to true.

useEffect(() => {
    checkEmpty && setCompleted(true)
}, [])

Question 2:

In the below code in onChange event i'm trying to invoke two function. I want to start the checkEmpty function only after the setValue function completes

onChange={ value=> {
    setValue(index, value),
    checkEmpty(value, index)
}}

Can anyone please help to solve the same.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Aggressive
  • 93
  • 3
  • 15

1 Answers1

0

Regarding your first question, in my opinion it's preferable to use an explicit if condition, but if you insist you should call the checkEmpty function by adding parenthesis: checkEmpty().
Without them, you're just checking if checkEmpty exists. Assuming it does - setCompleted(true) will always be invoked.

Secondly, if you want something to happen after a state changes, you can use the useEffect hook with the updated variable in its second argument.
So in your example, if you set value:

useEffect(() => {
  checkEmpty(value, index);
}, [value]);
GalAbra
  • 5,048
  • 4
  • 23
  • 42
  • 1
    First of all Thanks for the answer. For my second question there is a small change ie, i want to change state of 'completed' on onChange event as below. So when defining it inside useEffect will result in an infinite loop right? `onChange={ value=> { setValue(index, value), setCompleted(checkEmpty(value, index)) }}` – Aggressive Apr 26 '20 at 07:38
  • You're right. What's `completed`? Can it be stored in a `ref`? – GalAbra Apr 26 '20 at 08:17
  • Sorry it cant be. `completed` is used to update the UI when the `checkEmpty` returns true. – Aggressive Apr 26 '20 at 08:19
  • Then I'm afraid you're going to need to re-think your component design, so it makes sense with the hooks principles – GalAbra Apr 26 '20 at 08:35