Search code examples
reactjstypescriptnext.jsreact-hooksserver-side-rendering

Problem with calling function on server side in Next.js app


I have next problem with my Next app I have next method in my ArticleService class that call my sql db and has to return me all articles from my db

  async getArticles(): Promise<IArticle[] | ServiceError> {
    try {
      const reqArticles = await sql<IArticle>`
          SELECT * FROM articles
        `;
      const articles = reqArticles.rows;
      return articles;
    } catch (error) {
      return { message: "Cannot get articles" };
    }
  }

And here is a function that I call on frontend part

const getArticles = async () => await articles.getArticles();

Everything work absolutely great until I turn my page into "use client" and use next way to fetch data

  const [articles, setArticles] = useState<IArticle[]>();

  useEffect(() => {
    const fetchArticles = async () => {
      const articlesData = await getArticles();

      setArticles(articlesData as IArticle[]);
    };
    fetchArticles();
  }, []);

I'm sure that db is not empty and I'm sure that same function but with getting articles by id works great. Can somebody explain my how can I prevent this kind of error?


Solution

  • Ok gyus I've found out that accidentally next cached under the hood value of empty array, so I have to use import {unstable_noStore } from "next/cache" to solve this problem.