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

Time:04-14

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?

CodePudding user response:

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]);

CodePudding user response:

Try this :

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

CodePudding user response:

You can try this:

const router = useRouter();
const { pid } = router.query;
const [isMounted, setIsMounted] = useState(false);

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