Error encountered while retrieving data from an array of objects due to hydration issue

In my Nextjs project, I have a sidebar where I am trying to display 5 random posts from an array of objects. The function I defined is working correctly and showing the 5 posts, but I am encountering a Hydration error stating that the Prop alt does not match. Upon checking the console, I found that 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;

Answer №1

Give this code a shot :

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

const SidePanel = () => {
  const [shuffledPosts, setShuffledPosts] = useState([]);
  const [loadingPosts, setLoadingPosts] = useState(true);

  useEffect(() => {
    if (loadingPosts) {
      const shuffledArray = [...BlogData].sort(() => 0.5 - Math.random());
      setShuffledPosts(shuffledArray.slice(0, 5));
      setLoadingPosts(false);
    }
  }, [loadingPosts]);

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

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

export default SidePanel;

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

Developing a Customized Styling Guide Using Node.JS and User Specifications

Seeking a method to generate a personalized user style sheet utilizing input from users. Users can choose options like background colors, and the app will generate a custom style sheet based on their selections. Their input will be captured through HTML in ...

What is the best way to extract the value from a React date picker every time the dates are modified?

Currently, I am utilizing a React library known as react-date-picker and my goal is to retrieve the date every time it is modified. Below is the default code given by the library for selecting the date from a dropdown: import React, { Component } from "r ...

Effortless navigation through the document in both directions with seamless scrolling

To achieve a specific scrolling behavior on my webpage, I implemented the following function. Here is the code snippet: $(window).scroll(function(){ if ($(this).scrollTop() > 100) { $("html, body").animate({scrollTop: 700}, 500); re ...

Is it possible to integrate Vue.js within a web component?

Is it possible to utilize VueJS to control behavior within a web component? In other words, if the VueJS library is included as a script reference, can it be integrated in the same way as on a standard HTML page, but within the confines of a web componen ...

The deployment of Next.js on the Amplify platform encountered an error

Initiating SSR Build... 2021-08-28T10:20:02.691Z [ERROR]: Error: Command failed with exit code 1: node_modules/.bin/next build warn - No ESLint configuration detected. Run next lint to begin setup Browserslist: caniuse-lite is outdated. Please ...

Implementing the row delete function in MUI DataGrid using JavaScript

My grid has a delete icon button in each row, but it's not deleting the row. Can someone please help me with this issue? I'm working on a todo app where each row should have its own delete button. I'm struggling to connect the deleteTodo co ...

Ensure the hex game board contents are displayed correctly

After stumbling upon a hex board game project in Python here, I decided to give it a shot. However, my coding skills are a bit rusty and I'm struggling with creating a function that displays the board contents in the correct format. The desired output ...

Encountering unexpected values when utilizing UseContext in React

Utilizing useState within my component: context.js: const searchContext = React.createContext(); In this context, I initialized a state variable searchText with an initial value of an empty string. Header.js: import { useState } from "react"; ...

A guide to selecting the dropdown item labeled as (Select All) using Python and Selenium

edit: Trying to submit parameters for a database-generated report on this page. Successfully modified the start date in the first field using send_keys(), but unable to click on "(Select All)" for fields 3 and onwards, except one. In order to access the h ...

Creating a function while utilizing this conditional statement

Seeking guidance as I work on defining an 'explode' function. This function is intended to take a string input and insert spaces around all letters except the first and last ones. For example, if we call the function with the string Kristopher, i ...

How can I retrieve the width of a responsive React element during its initial rendering phase?

In my React project, there is a component called ResultList which is used to display products in a gallery format. The challenge I'm facing is determining the appropriate number of products to show per row based on the available width for the ResultL ...

Steps for converting a tsx file into a js file in React

Currently, I am in the process of a React Project and have numerous tsx files that I aim to convert for utilization as JavaScript within my project. What would be the best approach to achieve this task? ...

Error occurred during Apple Login using Next_Auth: OAuthCallback issue

Attempting to log in with Apple using NextAuth. Authentication is successful, but it redirects to /?error=OAuthCallback. The URL being used is: https://appleid.apple.com/auth/authorize?client_id=com.wheeleasy.org&scope=name%20email&response_type= ...

Using jQuery to conceal div elements that do not correspond to the chosen classes

My current challenge involves using jQuery to filter product search results by various criteria such as color, type, and size. My goal is to prevent users from ending up with "no results" by dynamically hiding filters that do not yield any matching product ...

Having trouble with your Ajax request to Google App Engine?

I've developed a GAE application that handles JSON requests and provides JSON responses. It's been tested successfully with an Android app, but now I'm attempting to create a JavaScript-based interface for web browsers. My goal is to send a ...

How can I append a query parameter to the URL in NextJS?

My goal is to include a query parameter whenever I enter some text in an input field and press the ENTER key. However, I'm struggling to determine the correct placement for this query parameter to function properly. Essentially, I want my URL to show ...

Use JavaScript to transfer list values to a textbox area

<!doctype html> <html> <head> <meta charset="utf-8"/> <title>My Title</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <s ...

Analyzing the AJAX response data against the content stored in the div

I need to compare and analyze data in order to determine if the div requires reloading. // <![CDATA[ $(function () { function reload (elem, interval) { var $elem = $(elem); var $original = $elem.html(); $.ajax({ ...

WebdriverIO and Cucumber: Make sure the promise resolves in under 10 seconds for function timeout

Currently, I am working on developing an application that involves a series of page navigations for users to complete information. To facilitate navigation to specific parts of the page, I attempted to create a generic step definition as a "background" ste ...

Utilizing the multer Express middleware in a standalone file

I successfully moved a basic middleware (isAuthenticated) to an external file, but I'm facing challenges transferring my multer upload. Although I recently learned how to separate them into different files, this task seems more complex. routes/index. ...