How to open Modal based on a function that changes the useState boolean in React?

I currently have the following useState and function:

const [displayTraits, setDisplayTraits] = useState(false)

    const feelingsFilled = () =>{
        const keysToCheck = ["anxiety", "mood", "cognition"]
        function validate(obj){
            try{
                if (Object.keys(obj).filter(key => keysToCheck.includes(key)).every(key => obj[key].counter > 0)){
                   setDisplayTraits(true);
                }
                else{
                   setDisplayTraits(false)
                }
            }
            catch(err){
                console.log('error')
                }
            }

        (validate(daily))
    }
feelingsFilled()

which I then try to hook up with a modal so that when my function feelingsFilled() return true and changes the DisplayTraits to True, then it will open.

        <Modal isVisible={displayTraits}  >

I am trying to run this but get the following error

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

Answer

I would need to make some assumptions on where the daily data comes from. If it is a changing prop or some other state, you can compute stuff based on that.

Using some state:

useEffect(() => {
  //computeYourStuffAndSetState
  const result = validate(daily);
  setDisplayTraits(result);
}, [daily]);
// The array param is a change-listener

Then you can bind your <Modal visible directly to the state variable, instead of a function.

Another example is to not use state at all and compute it everytime daily changes.

const showModal = useMemo(() => {
  return validate(daily);
}, [daily]);

useMemo and useEffect is a part of the built in react hooks.

Or you can just do something like:

const showModal = validate(daily);

This will also work, but will be less performant as it will recompute on every render