Unpacking in TypeScript and Next.js

I'm working with data from a PostgreSQL database:

https://i.sstatic.net/3nLrs.png

My goal is to retrieve the id, name, and content in a NextJS component as shown below:

export async function getServerSideProps() {
  const data = await prisma.note.findFirst()
  return {
    props: {
      userNote: data,
    },
  }
}
interface INote {
  id: number
  name: string
  content: string
}

const Home = ({ name, content, id }: INote) => {
  console.log(name)
  return <div>hello world</div>
}

However, when I try to access these values, they are coming up as undefined. What could be causing this issue?

Answer №1

One issue that needs attention is the props structure in the Home component.

{
  id: number
  name: string
  content: string
}

The correct props structure should be as follows:

{
 userNote: {
  id: number
  name: string
  content: string
 }
}

To address this, you have two options:

const Home = ({ userNote: { name, content, id } }: { userNote: INote }) => {

Alternatively, you can adjust your getServerSideProps function:

export async function getServerSideProps() {
  const data = await prisma.note.findFirst()
  return {
    props: data,
  }
}

In my experience, I recommend modifying it as follows:

export async function getServerSideProps() {
  const data = { id: 1, name: 'test', content: 'content' }
  return {
    props: {
      userNote: data,
    },
  }
}

interface INote {
  id: number
  name: string
  content: string
}

interface HomeProps {
   userNote: INote
}

const Home = ({ userNote: { name, content, id } }: HomeProps) => {
  console.log(name)
  return <div>hello world</div>
}

export default Home

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

Utilize string values as identifiers in type declarations

My Props type declaration currently looks like this: type Props<FormData> = { formData: FormData, sectionNme: keyof FormData, name: string } However, I am trying to modify it to look more like the following: type Props<FormData> = ...

Jest is experiencing issues with a mocked npm module that is unexpectedly returning empty objects

I am currently using a TypeScript environment and following instructions from this tutorial. The goal is to mock the socket.io-client implementation in my tests to simulate socket events for an instant messaging component. // __mocks__/socket.io-client.js ...

What is the best way to conduct a component test within the _app file in NextJS?

I'm encountering an issue with testing a bottomNavigation(footer) component rendered inside my _app file in nextJS. The error message I receive is "cannot find module". How can I effectively test this component? The specific error: 9 | import &apos ...

Having trouble debugging the current TypeScript file in VS Code because the corresponding JavaScript file is missing

In my current project using Visual Studio Code version 1.17, I am focusing on debugging the current typescript file. As part of my setup, I have a build task in place which generates a corresponding javascript file structure like so: src/folder1/folder2/m ...

How can I use a string variable in Angular 2 to create a dynamic template URL

@Component({ selector: 'bancaComponent', templateUrl: '{{str}}' }) export class BancaComponent implements OnInit { str: String; constructor(private http: Http) { } ngOnInit(): void { this.str = "./file.component.html"; } An ...

What could be causing React to generate an error when attempting to utilize my custom hook to retrieve data from Firebase using context?

Currently, I am restructuring my code to improve organization by moving data fetching to custom hooks instead of within the component file. However, I am encountering issues with the hook not functioning properly when used in conjunction with my context. ...

Mutations are not set up in the schema

Having an issue with setting up mutations in my project using npm, apollo server, and typeorm. Every time I attempt to create a mutation, I receive the error message "Schema is not configured for mutations". Searching for solutions has been fruitless as mo ...

Function is not triggered in React component

When the LoginPage calls AuthForm, the structure is as follows: function mapDispatchToProps(dispatch: Redux.Dispatch<any>) { return { signUpWithEmail: function(email: string, password: string) { // bla bla }, }; } handleForm ...

What is the best method for using template literals in a return statement?

I have been utilizing a template literal type in the following manner: type Greetings = `Hey ${string}` const string = 'Universe' function greet(string: string): Greetings { return 'Hey' + string } (Playground) However, I encounter ...

The TypeScript in the React-Native app is lacking certain properties compared to the expected type

I recently integrated the https://github.com/react-native-community/react-native-modal library into my project and now I need to create a wrapper Modal class. Initially, I set up an Interface that extends multiple interfaces from both react-native and reac ...

The ultimate guide to leveraging the power of Vitejs React TS template

When I try to specify absolute paths in the 'vite.config.ts' file, Vite seems to be unable to read the path properly and throws an error in the console. // vite.config.ts // Libraries import { resolve } from 'path' import { defineCo ...

ES6 Setters | warning TS2300: Identical identifier detected

Currently, I am developing a class for an Angular 2 component that involves the use of Input/Output decorators along with a setter as shown below: export class ItemDetails { // Assigning 'item' to a locally scoped property @Input(' ...

Learn how to utilize ng2-file-upload in Angular for uploading .ply files effortlessly!

I'm currently working on uploading various files using ng2-file-upload. I've been successful in uploading different file types like png and jpg, but I'm facing an issue with the .ply file extension. Can someone guide me on how to upload a fi ...

Indulging in the fulfillment of my commitment within my Angular element

In my Angular service, I have a method that makes an AJAX call and returns a Promise (I am not using Observable in this case). Let's take a look at how the method is structured: @Injectable() export class InnerGridService { ... private result ...

What makes React Native unique when it comes to handling multiple data inputs?

Apologies for my limited English skills. I am trying to structure multiple data entries by adding separate JSON lines for each input, but currently it updates the previous data instead of creating a new one. Below is the sample code I am working with. var ...

What guidelines should be followed when naming folders and files in next.js apps according to eslint settings?

a) Next.js has a unique convention of using underscores in the names of its main files, such as _app.js and _document.js. This raises the argument for utilizing snake_case. b) Within the GitLab repository, Next.js employs kebap-case for folder names. htt ...

Stop unnecessary updating of state in a global context within a Functional Component to avoid re-rendering

I am currently working with a Context that is being provided to my entire application. Within this context, there is a state of arrays that store keys for filtering the data displayed on the app. I have implemented this dropdown selector, which is a tree s ...

Evaluating the functionality of a pipeline that relies on various services

There is a custom pipe in my Angular application that sanitizes HTML, defined as follows: import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Pipe({ name: 'sanitiseH ...

Executing Angular E2E tests using the Protractor-Cucumber-Framework results in an abundance of peculiar cache files being generated

Within our Angular project, we have implemented the Protractor-Cucumber-Framework for conducting E2E tests. Upon completion of all E2E tests, not only does it create a results.json and results.xml file (which is expected), but it also generates numerous ob ...

Error: Axios header not refreshing automatically in React. User must manually refresh the page

After logging in, I want to update the JWT token in the header before redirecting to the home page. Login.tsx ... const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); const data = new FormData(event.curr ...