skip to Main Content

I have a state as below:

const [doctor, setDoctor] = useState<doctorStateProps | null>(null)

and then a useEffect function as follows:

useEffect(() => {
        if(!doctor){
            axios.get(`doctor/${id}`).then(({data}) => {
                setDoctor(data)
            })
        }
    }, [doctor])

I also have this function to enable the user to rate a doctor:

   const handleReview = async () => {
        try {
            if(text === '' || rating === 0){
                errorNotification('field cannot be empty')
            }else {
                await axios.post(`/doctor/${id}/review`, {text, rating, createdAt: moment(dayjs(date).toDate()).format('LL') })
                setText('')
                setRating(0)
                setGiveReview(false)
                setDoctor(null)
                successfulNotification('feedback received')
            }
        } catch (error) {
            errorNotification('error, please try again later')
        }
    }

The plan is for axios to get the doctor everytime a user refreshes the page, but i also want the doctor page to automatically update the doctor’s average rating when the user rates a doctor. However, the code above causes an infinite loop of re-renders.

I know this is not the ideal way of doing this but i cant figure out how to do it while simultaneously preventing the re-rendering. How do i go about this?

2

Answers


  1. Remove doctor from the dependency array of useEffect and leave it empty. Then the fethching will only run once (when your component get mounted). Should be simple enough for what you want to achieve.

    useEffect(() => {
            if(!doctor){
                axios.get(`doctor/${id}`).then(({data}) => {
                    setDoctor(data)
                })
            }
        }, []) // here, the dependency array is empty
    

    Also, why not use a single state for an object containing the necesarry fields (text, rating, etc…) instead of multiple states ?

    Login or Signup to reply.
  2. Just make a variable or state that checks if a user give a rating and put it in the dependency array.

    useEffect(() => {
            if(!doctor){
                axios.get(`doctor/${id}`).then(({data}) => {
                    setDoctor(data)
                })
            }
        }, [didUserGaveRating])
    

    Your question does not provide detailed information on your component tree.

    But you may be able to find the answer based on this method.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search