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

Encountering errors when attempting to preview a Strapi/Next.js starter after a fresh installation

Currently, I have a fresh installation of the strapi-starter-next-corporate starter app. On attempting to view a preview of an unpublished "secret" page, I encountered the following error: [develop:frontend] error - ReferenceError: locale is not defined [d ...

Determine the value added tax in your online shopping basket

Currently, I am in the process of developing a webshop for a pizzeria using Angular, and recently completed work on my cart component. One of the key features I wanted to incorporate was adding a 10% Value-Added Tax (VAT) for each item in the cart and incl ...

Issue with login form in IONIC: Form only functions after page is refreshed

Encountering an issue with my Ionic login form where the submit button gets disabled due to invalid form even when it's not, or sometimes displays a console error stating form is invalid along with null inputs. This problem seems to have surfaced afte ...

Updating an array using `setState` does not result in the array being updated

I created a component that uses the .map() method to render an array of students and has a button to shuffle and update the display. However, I'm facing an issue where the display does not update every time I click the button. const Home: NextPage = ...

"Exploring the dynamic duo of JHipster and master

I have utilized Jhipster's .jdl file to create all of my classes. Currently, I have two classes with a master-detail relationship. This setup displays the master record (let's say A) at the top of my form and a list/table of detail records (for e ...

Modifying SASS variable within an Angular 2 TypeScript project

How can I update the Sass color variable based on user input in Angular 2? I came across a helpful resource, but it doesn't include any examples specifically for Angular 2. Any assistance would be greatly appreciated. Thank you! ...

Angular Dynamic CSS Library by BPNM

I'm currently working with the Bpmn library to create a diagram. However, I've encountered an issue where I need to hide the palette in the diagram view dynamically. I attempted to achieve this by using @ViewChild in my TypeScript file to target ...

What is the mechanism behind Typescript interface scope? How can interfaces be defined globally in Typescript?

I'm diving into the world of Typescript and Deno, but I'm struggling to understand how interfaces scopes work. Here's the structure of my application: The first layer (App.ts) contains the core logic of my application. This layer can refer ...

Ways to eliminate double slashes from URL in Next Js. Techniques for intercepting and editing a request on the server side using getServerSideProps

Looking to manipulate a server-side request - how can this be accomplished? http://localhost//example///author/admin/// The desired output is: http://localhost/example/author/admin/ In Next Js, how can duplicate slashes in a URL be eliminated and req ...

I'm experiencing difficulties inserting data into my RECHARTS chart

I have several sets of data arrays from an API that I receive, and I need to use the [1] index of each array on the line and the [0] index on the axis of my chart. DATA SET 31) [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2 ...

Issues with loading Angular 9 application on Internet Explorer 11

Having trouble with my app not loading in IE 11 after adding ngx-treeview. Encountering the error (SCRIPT1002: Syntax error), Script Error Error point in vendor.js Unsure how to resolve this issue. Works fine in chrome and firefox, but in IE11 all I se ...

Can @Input() be declared as private or readonly without any issues?

Imagine you're working in an Angular component and receiving a parameter from its parent. export class SomethingComponent implements OnChanges { @Input() delay: number; } Would it be considered good practice, acceptable, or beneficial to designat ...

Properties of untyped objects in TypeScript are not defined

Here is the code snippet I've been working on: file.js const channel = {}, arr = [string,string,string]; for(let i = 0;i < arr.length;i++ ){ channel[arr[i]] = "Amo" //equal string value } I have an array that contains only string values, for ...

Angular 9: Implementing a synchronous *ngFor loop within the HTML page

After receiving a list of subjects from the server, exercises are taken on each subject using the subject.id (from the server) and stored all together in the subEx variable. Classes are listed at the bottom. subjects:Subject[] temp:Exercise[] = [] s ...

Utilizing TypedPropertyDescriptor to limit decorators in Typescript when using decorator factories

When it comes to restricting what a decorator can apply on, the standard method involves using a TypedPropertyDescriptor like so: export function decorator(target, key, TypedPropertyDescriptor<T extends ...>) {...} While this approach works well whe ...

Encountering Build Issue: "NgSemanticModule is not recognized as an NgModule" persists despite inclusion of dependencies and importing into primary module

I have posted my module, component, and package file here. I am attempting to implement a click event with ngif, but I keep encountering an error. The specific error message is "ERROR in NgSemanticModule is not an NgModule". I'm unsure if this error ...

Is it possible to compile a TypeScript file with webpack independently of a Vue application?

In my Vue 3 + Typescript app, using `npm run build` compiles the app into the `dist` folder for deployment. I have a web worker typescript file that I want to compile separately so it ends up in the root of the `dist` folder as `worker.js`. Here's wha ...

Develop a TypeScript class that includes only a single calculated attribute

Is it advisable to create a class solely for one computed property as a key in order to manage the JSON response? I am faced with an issue where I need to create a blog post. There are 3 variations to choose from: A) Blog Post EN B) Blog Post GER C) Bl ...

The TypeScript compiler is unable to locate the name 'window'

Within my Meteor/React project, I encounter the following line of code: let gameId = window.prompt("Please input the ID of the game you would like to load."); The TypeScript compiler presents an error during transpiling: Cannot find name 'window&apo ...

Error encountered in Next.js: Trying to access 'title' property of undefined

Currently, I am utilizing nextjs as my framework in an attempt to showcase titles using slug The code within my [slug].js file is as follows: import React, { useState } from 'react' import { useRouter } from 'next/router' const slug = ...