Home > Back-end >  Simple array.map causing hydration error in NextJs
Simple array.map causing hydration error in NextJs

Time:10-20

I have a strange hydration error in NextJS! I wonder if anyone can help me get to the bottom of it?

I have an object which gets processed synchronously. If i stringify this object and render it, i dont get an error.

but if, after stringifying it, i map through it, I get this hydration error.

What could be going on here?

const OpponentList = ({ opponents }: Props) => {
  return (
    <ul>
      <p>{JSON.stringify(opponents)}</p>  // NO ERROR


      {opponents.map((opponent) => {.    // HYDRATION ERROR
        return <li key={opponent.username}>{opponent.username}</li>;
      })}
    </ul>
  );
};


export default OpponentList;

CodePudding user response:

Stringfied form will not get parse through map. .map() is not the property of a string. It needs to be an array. So Either perform JSON.parse(JSON.stringify(opponents)) or use opponents.map directly (if opponents is an array).

CodePudding user response:

Since you are using Next.js, you can get rid of these issues by doing the asynchronous calls inside getServerSideProps method. If you do it like that, expecting data would be available in the client side when the client visits the page (No need to do the API calls from the client side).

Anyway if you really want to do it in client side, you could use something like this.

const OpponentList = ({ opponents }: Props) => {
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
   }, [])

  return mounted ? (
    <ul>
  
      {opponents.map((opponent) => {.    // HYDRATION ERROR
        return <li key={opponent.username}>{opponent.username}</li>;
      })}
    </ul>
  ): <div/>;
};


export default OpponentList;
  • Related