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

Javascript for Cordova utilizing WebSocket and incorporating client side certificates

I am looking to establish a secure SSL/TLS connection between my client and server, with only a specific authorized client allowed to connect. To achieve this, I have generated a client certificate using OpenSSL on the server for mutual authorization. The ...

Is there a way to change the color of a Material-UI snackbar without creating a new one for each color?

Is there a way to change the color of a snackbar in material-ui without creating a new one for each color? It seems that the example sandbox only has one color, while the others are static. ...

Is there a way to determine if media is actively playing in ReactJS? Let's find out!

I am currently working on building a media player in React and I'm looking to incorporate react media events, but the process has left me a bit perplexed. I could really use some guidance and assistance with this. import React, { Component } from &ap ...

Is it possible to have the Target='_blank' attribute open the link in a new window instead of a new tab?

Is there a way to achieve this? When using Firefox, the link opens in a new tab, which I prefer to avoid users having to adjust settings in their browsers. I am looking for a solution where a pop-up contact form appears whenever a user clicks on 'co ...

javascript containing the response message

I've created an Ajax function that retrieves a script from the server containing RSS feed information. I'm currently placing this response within a div using: $("#divId").html(responsetext); My goal is to execute the script included in the resp ...

Assistance with Validating Forms Using jQuery

I have a form located at the following URL: . For some reason, the form is not functioning properly and I am unsure of the cause. Any suggestions or insights on how to fix it? ...

How can I access the result of a getJSON promise within the $.when method?

I am working on a piece of code where I aim to collect data from 2 getjson calls and store it in an array only when both calls have successfully completed. However, I encountered the following error: resultFromUrl1.feed is undefined var entry1 = resultFro ...

In order to properly execute the JavaScript code, it is essential to create a highly customized HTML layout from the ER

I am currently utilizing this resource to create a gallery of images on my Rails page. Here is the HTML code required to display the images: <a href="assets/gallery/ave.jpg" title="Ave" data-gallery> <img src="assets/gallery/ave_tb.jpg" alt="Av ...

Using JavaScript to enhance and highlight specific items in a dropdown menu

I am looking for a solution to prevent duplicate selections in multiple select dropdowns. I want to alert the user if they have chosen the same value in more than one dropdown. Should I assign different IDs to each dropdown or is it possible to use just on ...

Update the webpage post a database entry without relying on the setTimeout() function in Javascript

Is there a method to automatically refresh the page after a new entry in the database without relying on Javascript's setTimeout or setInterval functions? Could an AJAX function or a MySQL function accomplish this task instead? Must we continuously ...

Unable to properly access required file path through HTML source

I have a confidential folder named 'inc' where I store sensitive files such as passwords in php connection files. This folder is located at the same level as the 'public_html' folder. I successfully accessed php files with database conn ...

Retrieve data using $http.get when an accordion group is expanded in AngularJS

Currently, I am utilizing Angular v1.2.0rc1 along with Angular-UI Bootstrap. [edit] My objective is to implement a load-on-demand feature with caching while incorporating an accordion functionality. The accordion group that I am using can be found here. ...

How to Retrieve the Default Value in a React Hook?

I have a certain input field with a default value assigned to it. <input type="text" name="default" value="one" /> To handle the state of this input, I am utilizing a react hook. const [def, setdef] = useState({Defaul ...

Avoid having logs displayed on the server end when utilizing console.log commands

Being new to JavaScript and Node.js, I am attempting to have my application output logs on the server side. getUser.onclick = function () { console.log('Server running at http://127.0.0.1:1337/'); var req = new XMLHttpRequest(); r ...

Running MERN on Heroku may result in unexpected errors

Currently, my project utilizes the MERN stack - incorporating NodeJS(Express), ReactJS, and mLab for the database, with webpack managing resources. Initially, I started with just ReactJS, but eventually added a backend for API functionality. Deploying so ...

Tips for updating row selection beyond the boundaries of the DataGrid in materialUI

Looking to update the DataGrid with the names of selected rows when a close button is clicked on the selected item. Any ideas on how to make this happen? https://i.stack.imgur.com/ctUZM.png In the example below, even though "Designer Cake" is removed fro ...

Switch between various components using multiple buttons in Next.js

I am in the process of creating a component that will display different components depending on which button the user selects. Here are the available “pages”: ` const navigation = [ { name: "EOQ", return: "<EOQgraph />" }, { nam ...

Error encountered when providing valid data types as arguments in a React/Typescript function

I am facing an issue when passing a string variable to a function. To address this, I have created an interface called MyMessageProps where I declare the message as a string. Subsequently, the function MyMessage utilizes this interface to return with the ...

How does the useEffect React hook perform its comparison process?

One of my favorite JavaScript expressions is: []==[] // false Let's now explore what the React documentation says about skipping side effects: React allows you to skip applying an effect if certain values have not changed between re-renders. To a ...

React - managing state across components using hooks

Looking for a way to have 2 components and a hook share the same state? Check out this simple CodeSandbox example here. Currently, the components seem to have separate states. Is there an easy solution to unify the state across all components? UPDATE: In ...