Error in next.js when navigating to a different route with incorrect image being

I am experiencing an issue with my [trainers].tsx page where the data loads correctly, but the image does not load properly. Instead, I can see a previous image from another page (../2) before the correct image is displayed.

For instance, when I navigate to ../1, the image loads as expected. However, when I navigate to ../2, I initially see the image from ../1 before the image for ../2 appears after a brief delay. What could be causing this problem?

...

export async function getServerSideProps({ params }: { params: any }) {
  const program = await API.getProgram(Number(params.trainers));
  return { props: { program } };
}

function Trainers(props: any): JSX.Element {
  const router = useRouter();
  const { trainers } = router.query;

  const { data } = useQuery(
    `program-${trainers}`,
    API.getProgram.bind(null, trainers),
    {
      initialData: props.program,
    }
  );

  return (
    <Layout>
      {JSON.stringify(data.preview)}
      <div className={"min-h-screen relative"}>
        <div className={"h-screen relative"}>
          <div className={"w-full h-screen bg-black"}>
            <Image
              src={data.preview}
              layout={"fill"}
              objectFit={"cover"}
              alt={"preview"}
            />
          </div>

         ...
      </div>
    </Layout>
  );
}

export default Trainers;

Answer №1

To ensure data is cleared when switching pages, consider implementing a method like this. You can also include a loader for the image if the data is empty.

async function getServerSideProps({ params }: { params: any }) {
  const program = await API.getProgram(Number(params.trainers));
  return { props: { program } };
}

function Trainers(props: any): JSX.Element {
  const router = useRouter();
  const [queryData, setQueryData] = useState(null)
  const { trainers } = router.query;

   const fetchData = () =>{
    let _data = null
    const { data } = useQuery(
      `program-${trainers}`,
      API.getProgram.bind(null, trainers),
      {
        initialData: props.program,
      }
    );
    if(data){
      _data = data
    }
    setQueryData(_data)
   }

  useEffect(() =>{
    fetchData()
    return () => {
      setQueryData(null)
    };
  }, [trainers]);

  return (
    <Layout>
      {queryData && JSON.stringify(queryData.preview)}
      <div className={"min-h-screen relative"}>
        <div className={"h-screen relative"}>
          <div className={"w-full h-screen bg-black"}>
            {queryData ? <Image
              src={queryData.preview}
              layout={"fill"}
              objectFit={"cover"}
              alt={"preview"}
            /> : <Loader/>}
          </div>

         ...
      </div>
    </Layout>
  );
}

export default Trainers;

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

Experiencing a repetitive occurrence of the error: "SyntaxError: Encountered an invalid or unfore

I've encountered a persistent error when attempting to execute my index.mjs file. Here is the content of my index.mjs file: import WebSocket, { WebSocketServer } from "ws"; import http from "http"; import express from 'express ...

The app bar menu items are failing to open the appropriate submenus in a correct

I am in the process of developing a frontend application using React16 along with the Material UI library. My current task involves creating a navigation bar at the top that contains multiple menu items. For this, I referred to the "simple menu" example o ...

Master the integration of Flask API with React-Redux by effectively implementing axios

Hello everyone! I am new to the world of React-Redux and I am currently working on a classification app using Flask API with ReactJS as the front-end. However, I am facing some issues when trying to call the API in Redux through the action file. The predi ...

Obtaining the current user's ID and adding it to the URL of a function in NodeJS

Is it possible to include the current user's ID in the URL parameter for my Express patch method? I know I can retrieve the ID from the Axios request, but how can I pass it without using a separate method? Any insights on this issue would be greatly a ...

Empty nested Map in POST request

I am currently working on a springboot application with a React/Typescript frontend. I have defined two interfaces and created an object based on these interfaces. export interface Order { customer_id: number; date: Date; total: number; sp ...

What are the properties used in functional components of React?

Seeking guidance on passing React component props to another component: interface IMyComponent { props: Props<any> } const MyComponent: FC = ({ props }) => { } Previously, I attempted to utilize the React.Props type after consulting this que ...

Having trouble with the getStatic Path function not functioning properly for the root URL "/" in Next.js?

Exploring the capabilities of Prismic and NextJS for the very first time. I'm currently facing an issue where the base URL localhost:3000/ is not loading as expected, while /About and /Pricing are functioning correctly. import { GetStaticPaths, GetSt ...

How do I retrieve the return value of another function in React?

I am working on a function called HandleCitiesArray where I need to access the myCitiesArray. To achieve this, I want to utilize the useSelector hook from Redux. Specifically, I aim to remove an object from initialState.myCities array. How can I go about ...

The BrowserRouter seems to be disregarding the forceRefresh property when it is assigned as a variable

Looking for a clever way to manage when my React SPA refreshes. I came across the forceRefresh prop in react-router-dom. It seems useful, but I'm facing an issue when trying to use a variable as its value. When set manually to true, everything functi ...

Disallow the generation of React components

I have a piece of code that successfully generates a to-do list, but I'm facing an issue. Even when I accidentally submit an empty form, new elements are still being created. How can I use useState to display a message preventing the submission of emp ...

Using a CSS gradient with a variable in React.js - A guide to implementation

Looking to incorporate the following CSS property into the Navlink component. In the CSS file, the property is usually written like this using gradient. .ele { background-image: linear-gradient(45deg, #808080 25%, transparent 25%), li ...

Tips for using Howler library in React to automatically play audio upon loading the page

I'm troubleshooting why the audio on my webpage won't start playing when the page loads, and instead only plays after a mouse click triggers an event. The audio works fine but I want it to automatically play as soon as the page is loaded. import ...

Having trouble rendering the React app; encountered an error: JSX contents are unterminated

I am currently facing an issue while trying to fetch data from an API in React using Axios. How can I ensure that useEffect functions properly? My objective is to create a page by fetching data from an API in React through Axios. I have designed a compon ...

Create a new web application to function as an API within Azure Active Directory

Can someone help me figure out how to set up a web application in Azure AD for access from other clients, such as SPA applications? I'm unsure of how to handle the authentication step in the flow. My initial thought was to register a web app (with web ...

Tips for maintaining the original value of a state variable on a child page in ReactJS. Keeping the initial value passed as props from the parent page

Whenever the 'isChildOpen' flag in the parent is true, my child page opens. The goal now is to ensure that the state variable filtered2 in the child component remains constant. While both filtered and filtered2 should initially receive the same v ...

I attempted to implement a CSS and Typescript animation for a sliding effect, but unfortunately, it isn't functioning

So I'm encountering an issue with this unique ts code: {/* Mobile Menu */} <div className="lg:hidden"> <button className="flex items-center w-8" onClick={toggleMenu}> {isMobileMenuOpen ? ( ...

How can we universally detect and resolve the user's language within a React/Next.js application using an Apollo client HOC?

Currently, I am developing an I18n module utilizing the Next.js framework (v5). The challenge I am facing is determining the user's default language universally in order to display the UI in that language. While it is relatively simple to resolve th ...

The Babel 5 plugin is encountering an issue due to an incompatible Babel version being used

Upon adding the relay-query plugin using yarn add -D babel-plugin-react-relay, and starting the development server, an error is encountered: Error: [BABEL] /Users/nemanja/sites/tictacturing/src/index.js: The (relay-query) Babel 5 plugin is being run with ...

What could be causing my Next.js layout to re-render?

I currently have a basic root layout set up in Nextjs (app router) that displays a navigation bar and the child components underneath it. ROOT LAYOUT import "./globals.css"; import type { Metadata } from "next"; import { Inter } from & ...

How can ExpressJS be used to direct users to individual standalone React applications?

I've spent a lot of time scouring the internet for a solution to my problem, but it seems like maybe I'm not asking in the right way. My project involves creating a Node-Express website where ReactJS is only needed on specific pages, while the r ...