React Query successfully retrieves the path, but unfortunately fails to render the image in the display

Currently facing an issue where I am trying to retrieve images from the backend using ReactQuery. Here is the ReactQuery code snippet:

export const useGetProductImagesByProductId = (productId: string) =>
    useQuery({
        queryKey: ['productImages', productId],
        queryFn: async () =>
        (await (await apiClient.get)<ProductImage[]>(`api/products/images/getImages/${productId}`)).data,
    })

The problem arises when fetching the image URLs separately from my products, as they are not being rendered properly.

I display my products in the ProductItem Component:

function ProductItem({product}: {product: Product}){
    const { data: images, isLoading: imagesLoading, error: imagesError } = useGetProductImagesByProductId(product.productId);

    if (imagesLoading) return <div>Loading images...</div>;
    if (imagesError) return <div>Error loading images: {imagesError.message}</div>;

    const imageSrc = images && images.length > 0 ? images[0].imageUrl : '';

    return( 
        <Card>
            <Link to={'/product/' + product.productId}>
                <img src={imageSrc} alt={product.name} className='product-image'/>
            </Link>
            <Card.Body>
                <Link to={`/product/${product.productId}`}>
                    <Card.Title>{product.name}</Card.Title>
                </Link>
            </Card.Body>
        </Card>
        
    )
}

If I input the URL directly into the img tag, it works fine:

<img src={"http://localhost:5045/Upload/Product/abeb7b1e-6705-454c-3316-08dc36b5c832/image.png"} alt={product.name} className='product-image'/>

EDIT 1

Upon testing, the array images returns the complete array, but images[0] and images[0].urlPath both return undefined. As a temporary fix, I used this solution:

<img src={String(images && images[0])} alt={product.name} className='product-image'/>

EDIT 2 The structure of the ProductImage type is as follows:

export type ProductImage = {
    imageUrl: string;
}

Answer №1

It seems like there may be a timing issue at play. Give this a shot

{
    images && <Card>
    <Link to={'/product/' + product.productId}>
      <img src={images[0].imageUrl} alt={product.name} className='product-image' />
    </Link>
    <Card.Body>
      <Link to={`/product/${product.productId}`}>
        <Card.Title>{product.name}</Card.Title>
      </Link>
    </Card.Body>
  </Card>
}

Answer №2

The problem was easily solved by realizing that the query returned a JSON format instead of a string, which was mistakenly inserted into the <img src=""> element. This caused an issue as the JSON only contained the string data and not a properly formatted image URL.

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

Load Order Possibly Disrupted by Arrival of Barrel Imports

When attempting to unit test my component, I keep encountering errors related to my import statements: Error: Cannot resolve all parameters for 'MyComponent'(undefined, FormBuilder). TypeError: Cannot read property 'toString' of undef ...

Struggling to make Cypress react unit testing run smoothly in a ReactBoilerplate repository

I have been struggling for the past 5 hours, trying to figure out how to make everything work. I even recreated a project's structure and dependencies and turned it into a public repository in hopes of receiving some assistance. It seems like there mi ...

Leveraging vuex in conjunction with typescript allows for efficient management of state in namespace modules,

I am currently integrating vuex with typescript and namespaces module in my project. Within this setup, I have two distinct modules: "UserProfile" and "Trips". So far, everything is functioning smoothly within the confines of each module. However, I have ...

Lerna and Create React App (CRA) problem: When using the command "lerna run --parallel start", the devServer does not initiate

I am currently working on managing 2 projects within lerna packages. One project is a package, and the other is a CRA website. When I run "yarn start" for each package individually, I can see the build folder and the website being loaded on the development ...

The count of bits is not producing the anticipated result

Attempting to tackle the challenge of Counting Bits using JavaScript, which involves determining the number of set bits for all numbers from 0 to N, storing them in an array, and returning the result Let me provide an explanation Input: n = 5 ...

Expandable Grid Sections in React MUI

Is there a way to create a grid layout where items with showDefault: true are always displayed at the top, and then users can click an arrow button to expand the grid and also show the items with showDefault: false? Any suggestions on how to achieve this? ...

Align watermark content to the far left side

Having trouble getting my watermark to align properly on the left side of my website's main content. Here is how it currently looks: https://i.sstatic.net/Nfhh5.png The issue arises when I resize the screen or switch to mobile view, as the watermark ...

When trying to access the DOM from another module in nwjs, it appears to be empty

When working with modules in my nwjs application that utilize document, it appears that they are unable to access the DOM of the main page correctly. Below is a simple test demonstrating this issue. The following files are involved: package.json ... "ma ...

What is the best way to establish communication with the root component in Angular?

I have implemented a modal in the root component that can be triggered from anywhere. However, I am facing a dilemma on how the bottom component can communicate with the top component without excessive use of callback functions. Root Component <contai ...

What is the method to retrieve the data type of the initial element within an array?

Within my array, there are different types of items: const x = ['y', 2, true]; I am trying to determine the type of the first element (which is a string in this case because 'y' is a string). I experimented with 3 approaches: I rec ...

Is there a way to safeguard against accidental modifications to MatTab without prior authorization?

I need to delay the changing of the MatTab until a confirmation is provided. I am using MatDialog for this confirmation. The problem is that the tab switches before the user clicks "Yes" on the confirmation dialog. For instance, when I try to switch from ...

Typescript error encountered in customized PipeLine class

I am currently developing a web scraping application using Puppeteer. In this project, I aim to create a PipeLine class that will take the current instance of the page and expose an add method. This add method should accept an array of functions with the t ...

The property you are trying to access is not defined on the enum type in Types

Looking to revise the TypeScript syntax of a lesson found at this link. I am aiming to extract a specific type from a union type using the following syntax: Actions['type'][ActionTypes.FEED_CREATE_POST] The available action types are defined a ...

What is the best way to loop through an array inside an object stored within another array using *ngFor in Angular 2?

Overview: My game data is structured as an array called 'game' with seven objects representing each round. Each round object contains details like 'roundNumber', 'title', 'players', and 'winner'. The &apos ...

What is the best way to assign a value to a class variable within a method by referencing the 'this' keyword?

Is there a way to set the state of this Ionic react app when displaying the outcome of a reset service? I am facing challenges with using this.setState({resetSuccess}) within a method due to scope issues. (Details provided in comments) Here is the relevan ...

Generate a series of HTTP requests using an HTTP interceptor

Is it possible to initiate an http request before another ongoing http request finishes (For example, fetching a token/refresh token from the server before the current request completes)? I successfully implemented this functionality using Angular 5' ...

Utilizing Input Data from One Component in Another - Angular4

As a newcomer to Angular, I'm facing an issue where I need to access a variable from ComponentA in ComponentB. Here's the code snippet that demonstrates what I'm trying to achieve (I want to utilize the "favoriteSeason" input result in the " ...

Creating a nested JSON file dynamically in Angular: A step-by-step guide

I am looking to dynamically generate a nested JSON file within an Angular project. The data will be extracted from another JSON file, with two nested loops used to read the information. Below is an example of the initial JSON file structure: { "data": [ ...

Angular - Issue with Function Observable<number> in Development

Currently, I'm working on writing TypeScript code for a component. Within this TypeScript class, I have created a function that is meant to return a number representing the length of an array. My goal is to have this function work like an Observable. ...

Connecting multiple TypeScript files to a single template file with Angular: A comprehensive guide

Imagine you are working with a typescript file similar to the one below: @Component({ selector: 'app-product-alerts', templateUrl: './product-alerts.component.html', styleUrls: ['./product-alerts.component.css'] }) expo ...