Next.js Discord

Discord Forum

Data disappears on tab navigation

Answered
Red-legged Kittiwake posted this in #help-forum
Open in Discord
Red-legged KittiwakeOP
my app page is behaving weirdly
on first page load
the data appears
then when i go to another tab and come back
the data is gone
Answered by riský
i was thinking smth like
function getPosts() {
  const dataPages = data?.pages.flatMap(...)
  if (dataPages.length === 0) return initialPosts
  if (dataPages == undefined) return initialPosts
  return dataPages
}
View full answer

58 Replies

Red-legged KittiwakeOP
This is the code for fetching the data
"use client";

import { INFINITE_SCROLL_PAGINATION_RESULTS } from "@/config";
import { ExtendedPost } from "@/types/db";
import { useIntersection } from "@mantine/hooks";
import { useInfiniteQuery } from "@tanstack/react-query";
import axios from "axios";
import { useSession } from "next-auth/react";
import { FC, useEffect, useRef } from "react";
import Post from "../Post";
import Spinner from "../ui/Spinner";

interface PostFeedProps {
  initialPosts: ExtendedPost[];
  categoryURL?: string;

  noPostsMessage: string;
}

const PostFeed: FC<PostFeedProps> = ({
  initialPosts,
  categoryURL,
  noPostsMessage,
}) => {
  const lastPostRef = useRef<HTMLElement>(null);
  const { ref, entry } = useIntersection({
    root: lastPostRef.current,
    threshold: 1,
  });
  const { data: session } = useSession();

  const { data, fetchNextPage, isFetchingNextPage } = useInfiniteQuery(
    ["infinite-query"],
    async ({ pageParam = 1 }) => {
      const query =
        `/api/posts?limit=${INFINITE_SCROLL_PAGINATION_RESULTS}&page=${pageParam}` +
        (!!categoryURL ? `&categoryURL=${categoryURL}` : "");

      const { data } = await axios.get(query);
      return data as ExtendedPost[];
    },

    {
      getNextPageParam: (_, pages) => {
        return pages.length + 1;
      },
      initialData: { pages: [initialPosts], pageParams: [1] },
    }
  );
continued:
  useEffect(() => {
    if (entry?.isIntersecting) {
      fetchNextPage(); // Load more posts when the last post comes into view
    }
  }, [entry, fetchNextPage]);

  const posts = data?.pages.flatMap((page) => page) ?? initialPosts;

  console.log(posts);

  return (
    <ul className="flex flex-col col-span-2">
      {posts.length > 0 ? (
        <>
          {posts.map((post, index) => {
            const votesAmt = post.votes.reduce((acc, vote) => {
              if (vote.type === "UP") return acc + 1;
              if (vote.type === "DOWN") return acc - 1;
              return acc;
            }, 0);

            const currentVote = post.votes.find(
              (vote) => vote.userId === session?.user.id
            );

            if (index === posts.length - 1) {
              // Add a ref to the last post in the list
              return (
                <li key={post.id} ref={ref}>
                  <Post
                    post={post}
                    commentAmt={post.comments.length}
                    category={post.category}
                    votesAmt={votesAmt}
                    currentVote={currentVote}
                  />
                </li>
              );
            } else {
              return (
                <Post
                  key={post.id}
                  post={post}
                  commentAmt={post.comments.length}
                  category={post.category}
                  votesAmt={votesAmt}
                  currentVote={currentVote}
                />
              );
            }
          })}
        </>
      ) : (
        <div className="flex justify-center items-center w-full h-[100px] text-muted-foreground">
          <span>{noPostsMessage}</span>
        </div>
      )}

      {isFetchingNextPage && (
        <li className="flex justify-center">
          <Spinner className="w-6 h-6" />
        </li>
      )}
    </ul>
  );
};

export default PostFeed;
Red-legged KittiwakeOP
on reload, it shows the posts, but if i navigate to another website (new tab) or another window (vscode), it displays the noPostsMessage until I reload the page
expectedly, the console.log(posts) returns an empty array when i navigate back from another tab
but idk what that behavior is
Red-legged KittiwakeOP
is it refetching the data?
i think i figured it out maybe
const posts = data?.pages.flatMap((page) => page) ?? initialPosts;
doesn't return initialPosts bc data?.pages.flatMap((page) => page) is [] not null or undefined
how do i make it consider []?
list.length will return 0 if it is empty
Red-legged KittiwakeOP
data?.pages.flatMap((page) => page) is of type ExtendedPost[]
import type { Post, Category, User, Vote, Comment } from "@prisma/client";

export type ExtendedPost = Post & {
category: Category;
votes: Vote[];
author: User;
comments: Comment[];
};
@riský list.length will return 0 if it is empty
Red-legged KittiwakeOP
tysm
is there a better way to write
i mean
you could return earlier with you know that it is 0 length..,
Red-legged KittiwakeOP
wdym
make a seperate function that goes that logic, and check for the length to be 0 and return initial, or the flatmap
and just run that in your componet
Red-legged KittiwakeOP
oh ok
@riský make a seperate function that goes that logic, and check for the length to be 0 and return initial, or the flatmap
Red-legged KittiwakeOP
like this?
alr ty
also you should do your flatmap code as a const before checks (simplify things as repeated code)
Red-legged KittiwakeOP
sry i haven't coded in a few months
do i remove the flatMap in the checks?
data?.pages.length == 0?
oh
set a variable
so it doesn't perform flatmap twice?
idk how your code is run (/ really how flatmaps even work)
Red-legged KittiwakeOP
me niether
i was thinking smth like
function getPosts() {
  const dataPages = data?.pages.flatMap(...)
  if (dataPages.length === 0) return initialPosts
  if (dataPages == undefined) return initialPosts
  return dataPages
}
Answer
but it kinda depends on how your code has the data
Red-legged KittiwakeOP
then it has ts error
possibly undefined
ahh ?.length
or do the undefined check earlier
Red-legged KittiwakeOP
either way, the posts below is possibly undefined
what is initialPosts typed as?
Red-legged KittiwakeOP
ExtendedPost[]
bruh im so dum
ohhh its because you didn't return dataPages
Red-legged KittiwakeOP
yeahh
does that work now?
Red-legged KittiwakeOP
it's fixed
yes
ty
you deserve the star
but your overall thread is solved?
Red-legged KittiwakeOP
yes
i haven't actually read most of your question, just that last bit where i commented on list.length
Red-legged KittiwakeOP
it worked so all is good
i like codeblocks for google more (as this bot is for indexing on google)