Home > Blockchain >  .map() function not returning anything when using routes
.map() function not returning anything when using routes

Time:10-06

I'm trying to create a multiple page web application using react-router-dom, but when I try to create the user list page (userlist.js), the .map() function is not returning anything that is inside the .map() function, but the last line before the .map() line is working fine, displaying <h1> with no problems.

Here's my App.js:

import './App.css';
import { useEffect, useState } from "react"
import axios from 'axios';
import React from "react"
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link
} from "react-router-dom"
import Home from './home'
import Userlist from './userlist'

function App() {
  return (
    <body>
      <header>
        <div className="divheadertitle">
          <h1 className="headertitle">Tree.io</h1>
        </div>
        <Router>
          <nav>
            <ul>
              <li><Link to="/">Home</Link></li>
              <li><Link to="/userlist">User list</Link></li>
            </ul>
          </nav>

          <Routes>
           <Route path='/userlist' element={<Userlist />/>
           <Route path='/' element={<Home />/>
          </Routes>
        </Router>
      </header>
    </body>
  )
}

export default App;

Here's my userlist.js:

import React from "react"
import axios from 'axios'
import { useState, useEffect } from "react"

function userlist() {
  const [listOfUsers, setListOfUsers] = useState([])

  useEffect(() => {
    axios.get('https://localhost:3001/userlist')
      .then((response) => {
        setListOfUsers(response.data)
      })
  }, [])

  return (
    <div className="userlistdiv">
      <h1>Lista de usuários:</h1>
      {listOfUsers.map((user) => {
        return (
          <div>
            <h1>Name: {user.name}</h1>  
            <h1>Age: {user.age}</h1>
            <h1>E-mail: {user.email}</h1>
          </div>
        )
      })}
    </div>
  );
}

export default userlist;

And finally, my back-end file, index.js:

const express = require('express');
const app = express();
const PORT = 3001;
const mongo = require('./mongo')
const usersModel = require('./models/userschema')
const cors = require('cors')
app.use(express.json())
app.use(cors())

app.get('/userlist', (req, res) => {
  usersModel.users.find({}).then((result, err) => {
    if (err) {
      res.json(err)
    } else {
      res.json(result)
    }
  })
})

app.get('/createUser', (req, res) => {
  const create = new usersModel.users({
    name: req.params.name,
    age: req.params.age,
    email: req.params.email
  })

  create.save()

  res.send('x')
})

app.listen(PORT, () => {
  console.log('Servidor rodando na porta '   PORT);
})

CodePudding user response:

Your routes need to be modified slightly. As the project's root folder is part of the path for each of the Route components, I'd also suggest using the exact attribute for the Home component, to ensure you won't run into any issues.

<Route exact path='/' element={<Home />} />
<Route path='/userlist' element={<Userlist />} />

I'm seeing both userlist and Userlist being used. This will create issues in JavaScript. Common convention in React is to use PascalCase for components throughout. You can keep the to attribute in Link and the path attribute in Route as lowercase, though. Some examples are included.

UserList.js
export UserList;
import UserList from './UserList';
function UserList { ... }
<div className='UserList'>...</div>

You might verify if you are calling with the right protocol.

axios.get('https://localhost:3001/userlist');

To avoid compilation warnings, set a key for the outer div within the map. You can use an id property from the data, or any other property that contains unique values in each entry.

<div key={user.id}>...</div>

CodePudding user response:

Have you tried to debug the content of listOfUsers using console.log for instance ? Try to put it one in the axios response, just before calling setListOfUsers(response.data). It looks like your array is empty, because your userlist server response can't find any user. What does your usermodel look like ?

Or maybe just try to rename your component in PascalCase :

function UserList() {
   ...
}

instead of

function userlist() {
   ...
}

Because your useEffect hook is maybe juste not called at all, since hooks can only been called from components or from hooks (i.e. function with PascalCase name returning an element, or functions starting with use)

  • Related