Santiago Spinetto Jung
Santiago Spinetto Jung

Reputation: 198

Get request axios React js useEffect is not working (Cannot find module './undefined')

I'm building a mock social network, and I'm stuck in an issue that I don't finish understanding. Here are the different results and code that I'm implementing.

The error:

Error: Cannot find module './undefined'
▼ 2 stack frames were expanded.
webpackContextResolve
C:/Users/sanjs/desktop/demo-react/src/assets sync /^/.*$:18
webpackContext
C:/Users/sanjs/desktop/demo-react/src/assets sync /^/.*$:13
▲ 2 stack frames were expanded.
Profile
C:/Users/sanjs/desktop/demo-react/src/components/ProfileSection/Profile.js:16
  13 | <div className='profile--image'>
  14 |     <Image 
  15 |        alt={`imagen de ${profile.title}`}
> 16 |        imgSrc={require(`../../assets/${profile.imagen}`)}
     | ^  17 |     />
  18 |   
  19 | </div>

The Profile component: receives profile props like an object to be displayed

                     <div className='content--content'>
                        
                        <div className='profile--image'>
                            <Image 
                               alt={`imagen de ${profile.title}`}
                               imgSrc={require(`../../assets/${profile.imagen}`)} <-- 

                               //if I delete this above line of code the error does not appear
                               //the data is displayed normally except the image of course 

                            />
                          
                        </div>
                            
                        ...
                           
                    </div>   

Then in ProfileDetail I query the data and implement the Profile component:

 const ProfileDetail = ({
     match
    }) => {

    const [ data, setData ] = useState({})
  
    useEffect(() => {
        async function getProfiles(){
           const result = await axios(
            `http://localhost:8001/api/profiles/${match.params.id}`,
           );
           setData(result.data);
           
        }
        getProfiles()
     }, [match]);
      
      console.log(data) // --> this logs an empty object {} the initial state. 
    return (
        <div className='profileDetail--container'>
                      
                   <Profile 
                       profile={data} 
                   />

                    ...
        </div>
    )
}

express server to get the profiles and profile by id:

const path = require('path');

const express = require('express');

const cors = require('cors');

const data = require('./data/profiles.json')

const app = express();

app.use(cors());

const port = 8001;

app.get('/api/profiles', (req, res) => {
    res.sendFile(path.join(__dirname, 'data', 'profiles.json'));
});

 app.get('/api/profiles/:id', function (req, res) {
    const profileId = Number(req.params.id)
    const getProfile = data.profiles.find((profile)=>profile.id === profileId)

    if(!getProfile){
      res.status(500).send('some error message')
    }else{
      res.json(getProfile)
    }
 })

app.listen(port, () => {
  console.log(`[profiles] API listening on port localhost:${port}/api/profiles.`);
});

In the browser this seems to work just fine... http//localhost:8001/api/profiles and http//localhost:8001/api/profiles/1 brings the data, but with some particularities. With the first URL the data is rendered in the browser like so:

{
  "profiles":[
       {
          "id":1,
          "name":"Rick",
          "lastName":"Sanchez",
          "tweets":["tweet1","tweet2"]
       },
        {
          "id":2,
          "name":"Morty",
          "lastName":"Smith",
          "tweets":["tweet1","tweet2"]
       },
       etc...
   ]
}

With the second one like so:

{id:1,name:"Rick",lastName:"Sanchez"} 

I can display the component deleting the line below, but without the profile image

imgSrc={require(`../../assets/${profile.imagen}`)}

first, the log is an {} and then prints twice the profile detail data as it should...otherwise prints the error message...

I hope I have clearly explained the problem, if anybody has a clue of what is going on, please let me know, thanks in advance.

Upvotes: 0

Views: 199

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53884

Such path ../../assets/${profile.imagen} doesn't exists in runtime, if you using CRA refer to how to add an image

import React from 'react';
import logo from './logo.png'; // Tell webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
function Header() {
  // Import result is the URL of your image
  return <img src={logo} alt="Logo" />;
}
export default Header;

If you want to do it dynamically, use the public (static) folder or import the related images and use a dictionary for example:

import logo1 from "./logo.png";
import logo2 from "./logo2.png";

const LOGO = {
  logo1: logo1,
  logo2: logo2,
};

function Header({ logoId }) {
  return <img src={LOGO[logoId]} alt="Logo" />;
}

Upvotes: 1

Related Questions