skip to Main Content

Somehow, there are non-stop requests going to the backend. I tried removing requiredFields from useEffects‘s dependencies, but then the frontend stops re-rendering. I had to reload the page to render new values. How do I fix it? Tell me if you need backend code also to help.

import React, { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import TitleForm from './TitleForm';
import DescriptionForm from './DescriptionForm'

const Course = () => {
    const { courseId } = useParams();
    const navigate = useNavigate()
    const [course, setCourse] = useState(null);
    const [requiredFields, setRequiredFields] = useState([])
    const [totalFields, setTotalFields] = useState(0)
    const [completedFields, setCompletedFields] = useState(0)
    const [completionText, setCompletionText] = useState("")
    const [isLoading, setIsLoading] = useState(true)

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await fetch(`http://localhost:3000/instructor/courses/${courseId}`, {
                    method: 'GET',
                    headers: {
                        authorization: `Bearer ${localStorage.getItem('token')}`
                    }
                });

                if (response.status === 401) {
                    return navigate("/signin")
                }

                if (!response.ok) {
                    throw new Error('Failed to fetch course data');
                }

                const data = await response.json();
                setCourse(data.course);
                setRequiredFields([
                    data.course.title,
                    data.course.description,
                    data.course.imageLink,
                    data.course.price,
                ]);

                setTotalFields(requiredFields.length);
                setCompletedFields(requiredFields.filter(Boolean).length);
                setCompletionText(`${completedFields}/${totalFields}`);
                setIsLoading(false)
            } catch (error) {
                console.error('Error fetching course data:', error);
                setIsLoading(false)
            }
        };

        fetchData();
    }, [requiredFields]);


    return (
        <div className='md:p-6'>
            <div className='flex items-center justify-between'>
                <div className="flex flex-col gap-y-2">
                    <h1 className='text-3xl font-semibold'>
                        Course Setup
                    </h1>
                    <span className='text-sm text-zinc-600'>
                        Completed Fields ({completionText})
                    </span>
                </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-16">
                <div>
                    <div className='flex items-center gap-2'>
                        <h2 className='text-xl font-semibold'>Customize Your Course</h2>
                    </div>
                    {!isLoading && <>
                        <TitleForm course={course} courseId={courseId} />
                        <DescriptionForm course={course} courseId={courseId} />
                    </>
                    }
                </div>
            </div>
        </div>
    )
}

export default Course

2

Answers


  1. I suggest you take a look at WebSockets. They basically are open connections between your front and backend through which messages can pass, typically to send updates from the backend to the frontend.

    I used ASP.NET SignalR as a WS library and I can only recommend it if you have a C# backend

    Login or Signup to reply.
  2. In your useEffect hook, you are updating the requiredFields with setRequiredFields for every successful fetch. While you also include requiredFields in your dependency array, this is why there is infinite get request.

    You should remove requiredFields from the dependency array.

    Edited:
    You may want to have a look into react query for live re-rendering. You can dynamically control how your application fetch the data with various options, for example:

    1. you can revalidate when there is an update detected (assuming you have POST/PUT request somewhere else), useQuery recognizes it by your given queryKey.

    2. you can also set a refetchInterval, where it will refetch at this frequency in milliseconds

    Installation: https://tanstack.com/query/v3/docs/react/installation

    On useQuery:
    https://tanstack.com/query/v4/docs/react/reference/useQuery

    A tutorial to start with:
    https://www.youtube.com/watch?v=yccbCol546c

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