Next.js Discord

Discord Forum

Shadcn Popover freeze

Answered
Ant posted this in #help-forum
Open in Discord
AntOP
I have Popover to select country and city, it's working when user select country im using API to get cities, 95% of them working fast but when i want to fetch for US,Brazil,France because of huge amount of data it freze page for 5-6 seconds then it opens, does anyone know how i can fix it?

21 Replies

AntOP
i tried 2 APIs but the same behaviour
If the API got a pagination system, you could reimplement a popover component to paginates the api using an infine scroll
Is this a server component ?
If yes, that shouldnt bug too much, that's weird that you've to wait that time
even if it's a client one.. that's weird.. can you provide a piece of code ?
AntOP
let country = form.watch("country");
  let city = form.watch("city");

  const handleCountryChange = useCallback(async () => {
    setIsCountrySelected(false);
    const selectedCountry = form.getValues("country");
    try {
      const response = await fetch(
        "https://countriesnow.space/api/v0.1/countries/cities",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ country: selectedCountry }),
        },
      );

      if (!response.ok) {
        throw new Error("Failed to fetch cities");
      }

      const data = await response.json();

      const cities = data.data;

      setCities(cities);
      setIsCountrySelected(true);

      return cities;
    } catch (error) {
      console.error("Error fetching cities:", error);
    }
  }, [country]);
thats multistep form, waiting to selected country to fetch cities
Tried also countrystatecity API but looks like this one is faster
and yes its client component
Answer
AntOP
oh first time heard about that
gonna check now
@joulev Is it due to the popover having to render too many items? If so, have a look at virtualisation
AntOP
Yea looks like thats the problem,because if i render some smaller country it works fast
Do you really need to refetch your data like this, can't Next cache it for you?
Caching doesn’t help with the app freezing when it tries to render 10k items
I know that, and your answer is probably the good one, i'm asking an another question rn
And In my memories, doing it like that, (I mean fetch in the component as it's written above) doesnt cache it at all
(nav will cache it but i'm talking about the server rn
AntOP
im using mostly server actions in this project but what u mean, how should i know which country user wanna add to location, its travel app user add custom location
prefetching all cities gonna be bad i think
AntOP
@joulev thanks, you saved my day 😄 . Now working perfect 🙂