Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

next.js: useEffect triggered twice when using param from router

I have this code

const router = useRouter();
const { pid } = router.query;

useEffect(() => {
        setLoading(true)
        fetch('my/endpoint/' + pid)
            .then((res) => res.json())
            .then((data) => {
                setData(data)
                setLoading(false)
            })
    }, [pid]);

I can see from the browser console a call to the api with pid = undefined, and right after another call with the actual pid value. How can I avoid the first call?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Dirty and fast solution, just controll if pid is defined

const router = useRouter();
const { pid } = router.query;

useEffect(() => {
     if(pid) {
        setLoading(true)
        fetch('my/endpoint/' + pid)
            .then((res) => res.json())
            .then((data) => {
                setData(data)
                setLoading(false)
            })
       }
    }, [pid]);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading