Next.js Discord

Discord Forum

Loading when search params change

Answered
Outis posted this in #help-forum
Open in Discord
Avatar
OutisOP
I'm fetching some data from my API based on the search params of my URL on a server component, I have a Link element that basically changes the URL from something like /movies?page=1 to /movies?page=2 and I'm loading more data every time. It adds more elements as you scroll down, almost like infinite scrolling but you load them manually. When I press the Link I want to change the loading state of my button. Can't seem to find something on the docs about this, I also have a scroll={false} prop on my Link
Answered by Outis
Found a solutionn from the docs https://nextjs.org/docs/app/api-reference/functions/use-router#router-events
const LoadMore = () => {
  const searchParams = useSearchParams();
  const page = parseInt(searchParams.get("page") ?? "1");

  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(false);
  }, [page]);
  return (
    <Center className="py-8">
      <Link
        href={`shows?page=${page + 1}`}
        scroll={false}
        onClick={() => setLoading(true)}
      >
        <Button loading={loading}>Load More</Button>
      </Link>
    </Center>
  );
};
export default LoadMore;
View full answer

1 Reply

Avatar
OutisOP
Found a solutionn from the docs https://nextjs.org/docs/app/api-reference/functions/use-router#router-events
const LoadMore = () => {
  const searchParams = useSearchParams();
  const page = parseInt(searchParams.get("page") ?? "1");

  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(false);
  }, [page]);
  return (
    <Center className="py-8">
      <Link
        href={`shows?page=${page + 1}`}
        scroll={false}
        onClick={() => setLoading(true)}
      >
        <Button loading={loading}>Load More</Button>
      </Link>
    </Center>
  );
};
export default LoadMore;
Answer