Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

swiper gets stuck after adding more objects to array. next and previous also doesnt work. update is not working either #7729

Closed
kkcodeberry opened this issue Sep 9, 2024 · 1 comment

Comments

@kkcodeberry
Copy link

Hi everyone,

Let me thank the community for the wonderful plugin first.
I am trying to use swiper in my project, where I have to get the next set of data when the user is on the last slide.
So, when I am trying to append the data. The swiper is getting stuck and not able to use previous and next button.
When I am in debug mode then functionality is working as intended.
I have tried update(). It executes successfully, but swiper still gets stuck. The same as using without update.
I have also tried destroy and initialize. But not able to find any solution.

If someone can shed a light on how this can be achieved, that would be really appreciable.

Below is my chunk of code :

import React, { useEffect, useState, useRef } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import { EffectCards, Navigation } from "swiper/modules";
import { ReactSVG } from "react-svg";
import close from "../assets/images/close.svg";
// Import Swiper styles
import "swiper/css";
import "swiper/css/effect-cards";
import "swiper/css/navigation";
import apiCategory from "../api/Category.js";
import { Link, useNavigate, useParams } from "react-router-dom";
import logo from "../assets/icons/favicon.png";
import SEO from "../components/common/SEO.jsx";
import JargonsCard from "../components/card/JargonsCard.jsx";

const JargonsCategoryCard = () => {
  const navigate = useNavigate();
  const { slug } = useParams();

  // const swiperRef = useRef(null);
  const [swiperRef, setSwiperRef] = useState(null);
  const [JargonsCategoryData, setJargonsCategoryData] = useState([]);
  const [totalSlides, setTotalSlides] = useState(0);
  const [loading, setLoading] = useState(true);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);
  const [activeIndex, setActiveIndex] = useState(0);
  const limit = 3;

  const [slideIndex, setSlideIndex] = useState(0);

  const loadMoreSlides = async () => {
    const nextPage = page + 1;
    const newData = await fetchSwiperData(nextPage);

    if (newData.length > 0) {
      setJargonsCategoryData((prevData) => [...prevData, ...newData]);
      setPage(nextPage);

      setTimeout(() => {
        // Ensure Swiper updates after new slides are appended
        swiperRef.update(); // Update Swiper
      }, 1000); // Small delay to ensure DOM updates first
    }
  };

  const fetchSwiperData = async (page) => {
    try {
      const response = await apiCategory.fetchChildCategoryBySlug(
        "jargons",
        slug,
        page,
        limit
      );
      //const response = await fetch(apiUrl);
      if (response.error) {
        throw new Error("Failed to fetch data");
      }

      return response?.data?.data?.posts; // Assuming the API returns a "slides" array in the response.
    } catch (error) {
      console.error("Error fetching swiper data:", error);
      return [];
    }
  };

  useEffect(() => {
    // Fetch initial swiper data
    fetchSwiperData(page).then((data) => {
      setJargonsCategoryData(data);
    });
  }, []);


  // create an event listener
  useEffect(() => {
    handleResize();
    window.addEventListener("resize", handleResize);
  }, []);

  useEffect(() => {
    if (swiperRef) {
      swiperRef.on("slideChangeTransitionEnd", () => {
        const swiperContainer = document.querySelector(".jorgon_card-swiper");
        if (swiperContainer) {
          swiperContainer.scrollTop = 300; // Reset scroll position
        }
      });
    }
  }, []);

  const handlePrevClick = () => {
    swiperRef.slidePrev();
  };

  const handleNextClick = () => {
    swiperRef.slideNext();
  };

  return (
    <>
      <SEO seoData={JargonsCategoryData?.seo} image={logo} />

      <div className="">
        <button onClick={() => navigate(-1)} className="p-4 block md:hidden">
          <ReactSVG className="max-w-1" src={close} />
        </button>

        {/* {loading ? (
          <p className="text-center">Loading Categories...</p>
        ) :  */}
        {JargonsCategoryData && JargonsCategoryData?.length > 0 ? (
          <div className="jorgon_card-swiper h-full h-[800px]">
            <Swiper
              // ref={swiperRef} // Add swiper reference
              onSwiper={setSwiperRef}
              effect={"cards"}
              navigation={true}
              onReachEnd={loadMoreSlides} // Trigger API call when reaching the end
              onSlideChange={(e) => setSlideIndex(e.realIndex)}
              allowSlideNext={true}
              loop={true}
              modules={[EffectCards, Navigation]}
              className="mySwiper h-full"
              cardsEffect={{
                perSlideOffset: isMobile ? 4 : 6, // Space between cards in px
                perSlideRotate: isMobile ? 1 : 2, // Rotation of cards in degrees
              }}
              observer={true}
              observeParents={true}
            >
              {JargonsCategoryData?.map((card, index) => {
                return (
                  <SwiperSlide key={index} className="bbb">
                    <Link to={card?.url}>
                      <img
                        className="rounded-3xl shadow shadow-stone-300"
                        src={card?.featuredImage}
                        alt={card?.title}
                      />{" "}
                    </Link>
                  </SwiperSlide>
                );
              })}
            </Swiper>
          </div>
        ) : (
          <p className="text-center">Category Data not available.</p>
        )}
        <button onClick={() => slideTo(3)} className="slide-500">
          Slide 500
        </button>
      </div>
    </>
  );
};

export default JargonsCategoryCard;

Copy link

Hello @kkcodeberry. Please provide a online reproduction by codesandbox or a minimal GitHub repository. You can fork one of our demos in codesandbox to get start. Issues labeled by missing demo will be closed if no activities in 3 days.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants