Interactive Image Component in React

I'm encountering an issue with my React code.

import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import RecipeService from "./RecipeService";
import RecipeProfileImg from "./RecipeProfileImg";
import "../../Assets/css/recipePage.css";

const RecipeComp = () => {

    const {id} = useParams();

    const [data, setData] = useState({});

    useEffect(() => {
        RecipeService.readRecipeById(id).then((res) => {
            console.log(res.data.type);
            setData(res.data);
        });
    }, [id]);

    function splitIngredients(ingrs){
        const pieces = ingrs.split(", ");
        const listItems = [];
        for(let i = 0; i < pieces.length; i++){
            const elem = <li>{pieces[i]}</li>;
            listItems.push(elem);
        }
        return listItems;
    }

    return(
        <div>
            <h1>{data.name}</h1>
            <RecipeProfileImg imgSrc={require("../../Assets/Images/" + data.type + "/" + data.url)} />
            <p id={data.url}>{data.type}</p>
            <p id={data.type}>{data.url}</p>
            <div className="listsBox">
                <label className="listLab">Ingredienti:
                    <ul className="listx">
                        {
                            splitIngredients(data.ingredients)
                        }
                    </ul>
                </label>
                <label className="listLab">Tempi:
                    <ul className="listx">
                        <li>Tempo di Preparazione: {data.preparationTime} min</li>
                        <li>Tempo di Cottura: {data.cookingTime} min</li>
                    </ul>
                </label>
            </div>
            <h3 className="prepTitle">Preparazione</h3>
            <p className="methodPar">{data.method}</p>
            <a href={'/recipes/delete/' + id}>delete me</a>
            <br />
            <a href={'/recipes/update/' + id}>update me</a>
        </div>
    );
}

export default RecipeComp;

In this specific React Component, I am facing an issue where the data.url and data.type values are correctly read in rows 2) and 3), but not in row 1). What could be causing this discrepancy?

1) <RecipeProfileImg imgSrc={require("../../Assets/Images/" + data.type + "/" + data.url)} />
2)            <p id={data.url}>{data.type}</p>
3)            <p id={data.type}>{data.url}</p>

Thank you for your assistance!

I have also attempted to pass these values using backtick strings,

../../Assets/Images/${data.type}/${data.url}
, but the result remains consistent - the data attributes are properly interpreted in all tags except within the img tag. The browser console displays an error message "Cannot find module './undefined/undefined'." Rest assured, the path (../../Assets/Images/" + data.type + "/" + data.url) is accurate.

Answer №1

The reason behind this is that useEffect mounts the state after the initial render, resulting in an empty object being returned during the first render (i.e., the initial state).

To address this issue, make sure to enclose your return statement within a conditional check.

return ({
    Object.keys(data).length>0 &&
    ....add the rest of your code here
})

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

Tips for adjusting the color of child elements when hovering over a card in Material UI

Having trouble changing the color of typography by hovering on a card? I tried many things, but finally decided to seek help here. When I remove the default color from typography and hover over the card, the text color changes as desired. However, I want t ...

I'm facing a challenge with displaying data on a dynamically created table using VueJS

I'm having an issue with dynamically generating a table using VueJS. The problem arises when creating the <th> elements. In order to set them up, I have a Vue component that is called by the addRow function. This component uses templates with v ...

Why is it that when accessing the property of an object within a computed object, it returns as undefined instead of the object itself? Which method would be more suitable in this

Salutations. To provide some context, my intention in posing this query is to dynamically render a child component within a form based on the selection made using the <app-selector> Vue component, as straightforward as that. To simplify matters, I ...

Positioning JQuery tooltips

I've been developing a simple tooltip tool (check out the fiddle link below), but I'm encountering some issues with positioning. My goal is to have the tooltip appear centered and above the clicked link, however right now it appears at the top le ...

Unable to successfully link filter outcomes with input in AngularJS

Here is the code snippet I am working with: <body ng-app=""> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {nam ...

Error caused by touch in JSX email field

There is a minor bug that doesn't impact the functionality, but it's present and bothersome. Within my react.js application, I have a signup form. Below is a simplified version: import { useState } from "react" import {signupApi} from ...

Can you explain the significance of polyfills in HTML5?

What exactly are polyfills in the context of HTML5? I've come across this term on multiple websites discussing HTML5, such as HTML5-Cross-Browser-Polyfills. Essentially, polyfills refer to tools like shims and fallbacks that help add HTML5 features ...

Tips for generating a subprocess with exec within a TypeScript Class

I am looking to automate the process of creating MRs in GitLab. When a button is clicked in my React/Typescript UI, I want to trigger command-line code execution within my Typescript class to clone a repository. However, every time I attempt to use exec, I ...

Error: Attempting to access a property of an undefined object resulting in TypeError (reading 'passport')

I am currently working on a project that requires me to display user profiles from a database using expressjs and mongoDB. However, I have encountered an issue and would appreciate any solutions offered here. Here is the code from my server: const express ...

Utilizing MenuItem for Navigation Links

I have been working on implementing a menu list for navigation within my application. The app and routes are functioning correctly, however I am encountering some warnings in the console when using the following code: {props.itemList.map((item, index) =&g ...

Traversing Through a Complicated JSON Structure

An application I developed can accept faxes in XML format and convert them into JSON objects to extract the necessary information, specifically the base64 string within the "file contents" variable of the document. Here is the code snippet: exports.recei ...

Receiving HTTP POST data using Classic ASP script

I'm currently working on a project and have come across an area where I am facing some challenges. Despite my best efforts, I haven't been able to find a solution using Google. In my ASP web application, I've added an HTML canvas that I nee ...

Every time I try to write not-found.js in the Next13 app router, I encounter an error

After creating a new file called not-found.tsx on top of the default file from create next app, everything seems to be working fine. However, I keep getting an error message in the console every second. Furthermore, when I try running the next app with ne ...

babel-eslint is causing issues preventing me from installing react

Recently I set up a new react App, only to encounter an issue with babel-eslint after adding a name to the react app. [email protected] start C:\Users\Samson Adedayo\Desktop\portfolio react-scripts start Upon investigation, ...

When I attempt to run several promises simultaneously with Promise.All, I encounter an error

My code contains a series of promises, but they are not being executed as expected. Although the sequence is correct and functional, I have found that I need to utilize Promise.all in order for it to work properly. dataObj[0].pushScreen.map(item => { ...

Toggle the visibility of a div based on whether or not certain fields have been filled

Having a form with a repeater field... <table class="dokan-table"> <tfoot> <tr> <th colspan="3"> <?php $file = [ 'file' => ...

Issue with jQuery.off when using a dynamic function name

I am currently implementing a modular pattern for writing my JavaScript code and it has been an enjoyable experience! However, I have encountered a challenging situation. My Namespace structure looks like this: var settings, handlers, objects, Namespace ...

Tips for creating incremental progress on a pop-up page?

I am looking for guidance on creating a page with specific functionalities. Here is what I have in mind: I want to implement a button that opens a popup when clicked. The popup should display static instructions and buttons for the user to progress throu ...

React: Remove a particular row from the table

I am currently working on a project that involves building a table component. Each row in this table is also a separate component. class FormulaBuilder extends Component { constructor(props) { super(props); this.state = ...

The React Native application is working fine on the emulator but is encountering some issues when trying

While the app runs smoothly on an emulator through Android Studio, I encounter an error when trying to run it from the CLI. error Failed to install the app. Ensure that you have set up the Android development environment properly: <a href="https://fac ...