Home > database >  Hydration error when fetching data from array of objects
Hydration error when fetching data from array of objects

Time:06-25

I am using Nextjs and there is a sidebar in which I am trying to get random 5 posts from an array of objects. The defined function is working fine and displaying 5 posts but I am getting a Hydration error showing Prop alt did not match. When I tried to display it on the console the alt value is different.

import Link from 'next/link';
import Image from 'next/image';
import { BlogData } from '../data/blogdata';


function getMultipleRandom() {
        const shuffled = [...BlogData].sort(() => 0.5 - Math.random());

        return shuffled.slice(0, 5);
    }

const Sidebar = () => {

    return (
        <>
            <h2 className='font-roboto text-3xl font-semibold pb-10'>Featured Posts</h2>

            {
                
                getMultipleRandom().map((val) => {
                    
                    return (

                        <div key={val._id} className='flex flex-col pt-5'>
                            <div className='w-56 pr-5'><Image src={val.featuredImage} alt={val.alt} width={1200} height={800} className=' rounded-3xl' /></div>
                            <Link href={`/blog/${val.slug}`}><a><h3 className='text-sm font-poppins font-medium hover:text-[#5836ed] transition-all duration-300'>{val.title}</h3></a></Link>
                        </div>
                    );
                })
            }

        </>

    )
}

export default Sidebar;

CodePudding user response:

try this code :

import Link from "next/link";
import Image from "next/image";
import { BlogData } from "../data/blogdata";
import { useEffect, useState } from "react";

const Sidebar = () => {
  const [shuffled, setShuffled] = useState([]);
  const [loading, setLoading] = useState(true); // anyting you want !!!

  useEffect(() => {
    if (loading) {
      const x = [...BlogData].sort(() => 0.5 - Math.random());
      setShuffled(x.slice(0, 5));
      setLoading(false);
    }
  }, [loading]);

  return (
    <>
      <h2 className="font-roboto text-3xl font-semibold pb-10">
        Featured Posts
      </h2>

      {loading ? <div>loading ... </div> : shuffled.map((val) => {
        return (
          <div key={val._id} className="flex flex-col pt-5">
            <div className="w-56 pr-5">
              <Image
                src={val.featuredImage}
                alt={val.alt}
                width={1200}
                height={800}
                className=" rounded-3xl"
              />
            </div>
            <Link href={`/blog/${val.slug}`}>
              <a>
                <h3 className="text-sm font-poppins font-medium hover:text-[#5836ed] transition-all duration-300">
                  {val.title}
                </h3>
              </a>
            </Link>
          </div>
        );
      })}
    </>
  );
};

export default Sidebar;

  • Related