javascriptreactjsnext.jshydration

Hydration Error Div in Div In react component


How can i solve Hydration error div in div problem.

I have a component who actually have 2 functionality - fetch and map. And i have faced hydration error, i don't know why i faced this issue! sometime it's give me a error and sometime it's not showed in my application. how can i solve this?

{
  tableBodyData?.map((item, index) => (
    <li key={index} className="font-[500] px-[6px] bg-[#2D5BFF] hover:bg-[#0d3deb] flex items-center justify-center gap-x-[2px] duration-100 rounded-[4px] leading-[24px] text-white cross-magic cursor-default text-[12px] border-none outline-none hover:extraDarkBlue">
      {item?.tag}
      <span onClick={() => handleDeleteTags(item)} className="cursor-pointer ml-2"> 
        <SettingsWhiteCircleCross />
      </span>
    </li>
  )
}

Solution

  • The hydration error you're encountering might be due to the fact that your component is rendering on the client before the data is available, leading to an attempt to render data?.data when data is still undefined. To handle this, you've added a condition before the map function to ensure that data?.data is not undefined before rendering. However, this approach can sometimes lead to complications, such as the hydration error you're experiencing.

    To solve this issue in a more elegant way, you can handle the loading state and error state explicitly in your component. Here's how you can modify your component to handle these cases:

    import { useFetch } from "@/utils/CustomFetcher";
    import endpoint from "@/utils/endpoint";
    import ServerOptions from "@/utils/ServerOptions";
    import React, { useState } from "react";
    
    export default function ServersListDropdown() {
      const [selectedItem, setSelectedItem] = useState();
      const { data, error, isLoading } = useFetch(
        `${process.env.NEXT_PUBLIC_CLOUD_URL}${endpoint.dashboard.get_server_list}`
      );
    
      if (isLoading) {
        return <div>Loading...</div>;
      }
    
      if (error) {
        return <div>Error: {error.message}</div>;
      }
    
      return (
        <div className="h-full bg-white flex rounded-[4px] w-[277px] mr-[12px]">
          <ServerOptions
            label={`Servers`}
            setDropdownValues={setSelectedItem}
            options={data?.data}
          />
        </div>
      );
    }