Home > Mobile >  Next JS - how to give object a unique id?
Next JS - how to give object a unique id?

Time:09-08

I am trying to give my object a unique id by using Math.random, but I am getting the error below. If I change the Math.random to a integer like 4, the error goes away but I need the id to be unique.

Unhandled Runtime Error

Error: Text content does not match server-rendered HTML.

See more info here: https://nextjs.org/docs/messages/react-hydration-error
const data = [
    {
        id: Math.random(),
        sentence: 'hello there',
    },
    {
        id: Math.random(),
        sentence: 'bye!',
    },
]

export default function Index(props) {
    return (
        <div>
            <h1>{data[0].id}</h1>
            <h1>{data[0].sentence}</h1>
            <h1>{data[1].id}</h1>
            <h1>{data[1].sentence}</h1>
        </div>
    )
}

CodePudding user response:

Use the uuid npm package to generate unique id's.

import { v4 } from "uuid";

const data = [
    {
        id: v4(),
        sentence: 'hello there',
    },
    {
        id: v4(),
        sentence: 'bye!',
    },
]

CodePudding user response:

First, the page is rendered on the server, then returned to the client to rehydrate, two times initializing data would cause different ID values. This is called hydration mismatch, which is solved by useId in React 18

But using NextJS, you could solve this problem by initializing data on server to keep it consistent

export default function Index(props) {
  return (
    <div>
      <h1>{props.data[0].id}</h1>
      <h1>{props.data[0].sentence}</h1>
      <h1>{props.data[1].id}</h1>
      <h1>{props.data[1].sentence}</h1>
    </div>
  );
}

export async function getServerSideProps(context) {
  return {
    props: {
      data: [
        {
          id: Math.random(),
          sentence: 'hello there',
        },
        {
          id: Math.random(),
          sentence: 'bye!z',
        },
      ],
    }, // will be passed to the page component as props
  };
}

Stackblitz demo

References

getServerSideProps

  • Related