apparently, it is considered a best practice if you can split all the data fetching functions to a separate folder called services and put all the functions there then use them in the project
However, I couldn't make it happen with Next.js
The function works when I put it inside the same component I want to render the data inside it, but doesn't work when I put the function in a separate folder and export it.
I get this error:
TypeError: Cannot read properties of undefined (reading 'map')
I think it is because the data props are not being passed to the component correctly.
below are the working and none working examples :
the Working example:
inside index.tsx file :
export async function getStaticProps() {
const response = await fetch(
`https://api.github.com/users/abdurrahmanseyidoglu/repos`
);
const data = await response.json();
if (!data) {
return {
notFound: true,
};
}
return {
props: {
data,
}, // will be passed to the page component as props
};
}
const Home = ({ data }) => {
return (
<>
<ul>
{data.map((repo) => (
<li key={repo.id}>{repo.name}</li>
))}
</ul>
<p className="max-w-5xl m-auto text-justify mt-2 border rounded p-3 shadow-lg">
Working Example
</p>
</>
);
};
export default Home;
Not Working example:
inside services/getUserRepos.ts :
export async function getStaticProps() {
const response = await fetch(
`https://api.github.com/users/abdurrahmanseyidoglu/repos`
);
const data = await response.json();
if (!data) {
return {
notFound: true,
};
}
return {
props: {
data,
},
};
}
inside index.tsx file :
import { getStaticProps } from "../services/getUserRepos";
const Home = ({ data }) => {
return (
<>
<ul>
{data.map((repo) => (
<li key={repo.id}>{repo.name}</li>
))}
</ul>
<p className="max-w-5xl m-auto text-justify mt-2 border rounded p-3 shadow-lg">
None Working Example
</p>
</>
);
};
export default Home;
How can I make it so I can pass the fetched data from a separate folder to my index.tsx file
getStaticPropsneed to be exported from the page file. You import it and don't do anything with it. Soindex.tsxhas no exported functiongetStaticPropsand therefore doesn't work. nextjs.org/docs/basic-features/data-fetching/get-static-propsgetStaticPropsfunction into a separate function/file, for reusability. Import the function and use is within thegetStaticPropsfunction, which you then export.Error: Error serializing `.data` returned from `getStaticProps` in "/". Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.