Search code examples
javascriptreactjsstateconditional-operatoruse-effect

Delay ternary operator from checking React State till useEffect Hook finishes


I hope I'm phrasing my question the right way. Here is what I have going on.

I have a ternary operator set up like the code below. It checks for the existence of state and opens a Modal form if the state does not exist.

   { !selectPet && selectClient ?
                <Modal>
                    <Form>
                       <form stuff/>
                    </Form>
                </Modal> 
              : null 
   }

selectPet is set in the useEffect hook like this.

function clientsPets() {
        if (selectClient !== undefined) {
            API.getClientPets(selectClient._id)
                .then(res => {
                    if (res.length > 0) {
                        setSelectPet(res) // Right here is where the selectPet is being set
                        setActivePet(res[0])
                        API.getPetSessionsByPetId(res[0]._id)
                            .then(res => setTrainingSessions(res))
                            .catch(err => console.log(err))
                    } else {
                        return
                    }
                })
                .catch(err => console.log(err))
        } else { history.push("/") }
    }

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

What I am having trouble with is when the page first loads the Modal is displayed for less than a second before the useEffect finishes. Logically Im not sure how to fix this. Could I set some sort of interval before checking the selectPet state or is there a better way to resolve this?


Solution

  • What are the initial state values for selectPet and selectClient? If you don't want the modal to appear until your API calls are done and those state values have been updated, just make sure the initial values are set such that the ternary will skip to the "else" block and render null instead of the modal.

    Bear in mind, since the first condition in the ternary is !selectPet, either the initial value of selectPet must be "truthy", or selectClient's initial value must be falsy, in order to skip to the "else" block of the ternary.