What is the process for bringing my API function into a different Typescript file?

I've successfully created a function that fetches data from my API. However, when I attempt to import this function into another file, it doesn't seem to work. It's likely related to TypeScript types, but I'm struggling to find a solution.

Below is the function responsible for retrieving API information:

import { InferGetStaticPropsType } from "next";

type Post = {
  project: string;
};

export const getStaticProps = async () => {
  const res = await fetch("http://localhost:3100/");
  const posts: Post[] = await res.json();

  return {
    props: {
      posts,
    },
  };
};

function Blog({ posts }: InferGetStaticPropsType<typeof getStaticProps>) {
  return (
    <>
      <h3>Hi</h3>
      {console.log(posts)}
    </>
  );
}

export default Blog;

The issue arises when I try to call the above code, Blog, in my root index.tsx file:

import type { NextPage } from "next";

import Blog from "./blog";

const Home: NextPage = () => {
  return (
    <>
      <Blog />
    </>
  );
};

export default Home;

This is the error I'm encountering: https://i.stack.imgur.com/OMZC6.png

If anyone wants to view the complete code here it is, with the API located in the express-api folder.

Answer №1

getStaticProps is specifically designed for pages in Next.js. This means that if your Blog component is not designated as a page, the function will not execute.

However, one workaround could be to move the data fetching logic to your Home page and then pass the retrieved data to the Blog component:

import { NextPage, InferGetStaticPropsType } from "next";
import Blog from "./blog";

type Post = {
  project: string;
};

export const getStaticProps = async () => {
  const res = await fetch("http://localhost:3100/");
  const posts: Post[] = await res.json();

  return {
    props: {
      posts,
    },
  };
};

const Home: NextPage = ({ posts }: InferGetStaticPropsType<typeof getStaticProps>) => {
  return (
    <>
      <Blog posts={posts} />
    </>
  );
};

export default Home;
function Blog({ posts }) {
  return (
    <>
      <h3>Hi</h3>
      {console.log(posts)}
    </>
  );
}

export default Blog;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modify the standard localStorage format

I'm encountering a dilemma with my two applications, located at mysite.com/app1 and mysite.com/app2. Both of these apps utilize similar localStorage keys, which are stored directly under the domain "mysite.com" in browsers. This setup results in the l ...

Leveraging the power of the map function to manipulate data retrieved

I am working on a nextjs app that uses typescript and a Strapi backend with graphql. My goal is to fetch the graphql data from strapi and display it in the react app, specifically a list of font names. In my react code, I have a query that works in the p ...

Discover the mistake during the creation of the next.js application build

Trying to build my next.js file, but encountering an error: ./pages/city/[city].js 21:20 Error: React Hook "useRouter" is called in function "city" that is neither a React function component nor a custom React Hook function. React ...

Extract JSON values based on a given condition

I am working on a Typescript project that involves an array and a JSON object. I need to extract the value of a property from the object based on another property's value being in the array. Here is the array: let country: string[] = [ 'AR' ...

Encountering a Next.js Strapi error. TypeError: Fetch request unsuccessful

An error occurred during module build: UnhandledSchemeError: The plugin does not support reading from "node:assert" URIs (Unhandled scheme). Webpack natively supports "data:" and "file:" URIs. You might require an extra plugin to handle "node:" URIs. ...

Challenge encountered with implementing Next-Auth's authorize function in TypeScript

Encountering a type error in the authorize function while using NextAuth with CredentialsProvider export const authOptions : NextAuthOptions ={ session : { strategy: "jwt" }, providers : [ CredentialsProvider({ async authorize( c ...

A guide on using .map() with meta tags in Next.js

My goal is to map the content of meta, but currently my code is replicating multiple instances of the entire meta tags. Here is the code I have: {general.head.articleAuthor.en.map(( ) => ( <meta property="article:author" content={general.h ...

Troubleshooting Typescript compilation issues following an upgrade to a React Native project

I am facing a challenge while updating a react native project from version 0.63.3 to 0.67.0. When attempting to run npm run tsc, I encounter numerous errors indicating that the typescript packages are not compatible with their original packages. Here is a ...

Customizing default attribute prop types of HTML input element in Typescript React

I am currently working on creating a customized "Input" component where I want to extend the default HTML input attributes (props). My goal is to override the default 'size' attribute by utilizing Typescript's Omit within my own interface d ...

Testing in Vue revealed an unexpected absence of data

I am facing difficulties when it comes to creating tests. Currently, I have a view that is supposed to verify an email address using an authentication code. At the moment, the view exists but no connection is established with an email service or code gener ...

What is the best way to implement custom sorting for API response data in a mat-table?

I have been experimenting with implementing custom sorting in a mat-table using API response data. Unfortunately, I have not been able to achieve the desired result. Take a look at my Stackblitz Demo I attempted to implement custom sorting by following t ...

In next.js, when using the DELETE method, make sure to utilize a query parameter rather than

As I work on developing an API, I have encountered an issue with the delete functionality not functioning as expected. When sending a request, I receive a response from this URL: http://localhost:3000/api/admin/categories?id=1 instead of from this URL: ht ...

Error: The page "..." contains an invalid "default" export. The type "..." is not recognized in Next.js

Currently, I have a functional component set up for the Signup page. My goal is to define props within this component so that I can pass the necessary values to it from another component. This is my current approach: export default function SignupPage({mod ...

Next.js Dynamic Routing allows you to create dynamic routes by adding

Let me first show you my file structure before I explain my question. app| |->api| |->user| |->[userId].js [userId].js: export function GET(req){ return new Response("Hello")} This is the backend file st ...

The program is requesting an expression involving the user's username

https://i.stack.imgur.com/tf1QD.png What is causing the issue with trying to use user.username? as an expression? While user.username returns a string of the User's username, I am unable to index it into listOfPlayers[]. client.on("messageReacti ...

Next.js SSR application with an Intl Polyfill

Is there a way to implement the polyfill for Intl in a Next.js application? We are facing issues with some Chinese browsers that don't support it, and our use of react-intl requires Intl to function properly. ...

NextJS 13 beta: A guide on establishing communication between the client child and parent server components

It's clear that I need to brush up on some basic concepts here. In my parentServerComponent, I'm attempting something like this: parentServerComponent.js: // some logic and data fetching happening here return ( <childClientComponent1 /&g ...

The error message "tsc not found after docker image build" appeared on the

My goal is to deploy this program on local host. When I manually run "npm run build-tsc," it works successfully. However, I would like Docker to automatically run this command when building the image. Unfortunately, I receive an error saying that tsc is no ...

Next.js - utilizing dynamic API routes within nested folders

Currently, I am working on developing a basic API that reads a local JSON file. My goal is to create a dynamic API that can adjust based on the specific calls it receives. Within my API folder structure, I have: api --book ---[id].js ----content -----[id ...

Retrieve an SVG file from the internet and incorporate it as a <svg /> element within a React component in a Next.js project

I have a situation where I am trying to style .svg files within an API being used by a NEXT.js application. Currently, the files are loaded using <img src="https://api.com/image.svg" />, but this method does not allow for styles to be appl ...