Roma Kim
Roma Kim

Reputation: 371

Having trouble prefetching data in Next.js

I have a simple dummy API that returns an array of objects dummy data such as:

// api/projectsdata.js

    export default function handler(req, res) {
      res.status(200).json([{...},{...},{...}]
    }

My fetch API looks like this:

import { useEffect, useState } from "react";

const ProjectsUtil = () => {
  const [data, setData] = useState(null);

  const fetchData = async () => {
    try {
      const response = await fetch("http://localhost:3000/api/projectsdata");
      const data = await response.json();

      if (response.ok) {
        setData(data);
      }
    } catch (error) {
      throw new Error(error);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  return data !== null && data;
};

export default ProjectsUtil;

I try to fetch using a two helper functions below:

export const getAllProjects = () => {
  const data = ProjectsUtil();
  return data;
};

export const getProjectByName = (name) => {
  const data = getAllProjects();
  return data.filter((project) => project.name === name);
};

In another component I'm trying to prefetch and consume the data such as:

const SingleProjectDetails = (props) => {
  return <ProjectDetails props={props.projectData[0]} />;
};

export function getStaticProps(context) {
  const { params } = context;
  const { id } = params;
  const projectData = getProjectByName(id);

  return {
    props: {
      projectData: projectData,
    },
    revalidate: 600,
  };
}

export function getStaticPaths() {
  const projectsData = getAllProjects();

  return {
    paths: projectsData.map((project) => ({
      params: {
        id: project.name,
      },
    })),
    fallback: true,
  };
}

I get an error: TypeError: Cannot read properties of null (reading 'useState').

The confusing part is that my fetching API functions works fine in other components. Also if I initialize dummy data as a plain array of object and not a call from API, everything works fine. What seems to be a problem? Is prefetching an API not allowed?

Upvotes: 0

Views: 588

Answers (1)

Lav
Lav

Reputation: 11

You are calling a Function component inside a regular function. That doesn't work.

Instead, you could extract out the fetchData function into top level function, return the data instead of setting it via a setter and use this fetchData function inside your getAllProjects function.

Don't forget to await the data.

Upvotes: 1

Related Questions