Next.js Discord

Discord Forum

#swiper reload scripts when page change

Unanswered
Sphynx posted this in #help-forum
Open in Discord
Avatar
SphynxOP
I have my slider on my project pages, inside a component <Slider/>,

This is the script to launch it:

 const swiperElRef = useRef(null);
  let mySwiper;
   useEffect(() => {

            const swiperEl = document.querySelector('swiper-container');
            const swiperParams = {
            (...)
            on: { 
            init() {
                console.log('launch total slider');
            },
            }
          };
          
          Object.assign(swiperEl, swiperParams);
          swiperEl.initialize(); 
           
        }, []);


When I navigate to information, and I come back to any project page, it works, but if I navigate from project to project, it doesn't refresh the number of slide etc, and it bugs.

I've added this code to attempt to refresh it when route changes, and sometimes it works, sometimes not at all. Has anyone an idea on how I could fix this?


 useEffect(() => {


          const swiperParams = {
          (...)
          on: { 
          init() {
            console.log('RE RUN SLIDER slider');
          },
          }
        };
 
        const incrementCompleteCount = (url) => {
          console.log('routeChangeComplete', url);
             const swiperEl = document.querySelector('swiper-container');
              if(swiperEl){
                Object.assign(swiperEl, swiperParams);
                swiperEl.initialize();
              }
      };
       router.events.on('routeChangeComplete', incrementCompleteCount);

     

      }, [router.events]);

0 Replies