Miles
Miles

Reputation: 21

fetching data with useState and useEffect in react.js

with this code I'm able to retrieve users' data and console.log it but unable to pass or fetch it into the data array and render users' info using data.map as it console.logs empty array and throws out an error: Uncaught (in promise) TypeError: data.map is not a function. How can I fetch this data to the data array? Thanks in advance!

import React, { useState, useEffect } from 'react';
import './welcome.css';


function Welcome (){
  const [data, setUsers] = useState([])

  useEffect(() => {
    fetch('http://localhost:4000/users')
    .then((res) =>  res.json())
    .then(users => setUsers({users}, console.log(users), console.log(data)))
      
    }
  )
  

  return(
    <div className='welcome'>    
    <ul >
      {data.map(user => 
        <li  className='user' key={user._id}>{user.Username}</li>  
      )}

    </ul>

    <h1>Welcome to GRM</h1> 
    <h1>Explore the music world</h1>

  </div>
  )
}


Upvotes: 0

Views: 2966

Answers (3)

Miles
Miles

Reputation: 21

for those who are running into the same problem, here's what worked for me:

export default function Welcome (){
  const [data, setUsers] = useState([])
  useEffect(() => {
    fetch('http://localhost:4000/users')
    .then(res => (res.json()))
    .then(({users}) => setUsers((users)))
  
  }) 
  return(
    <div className='welcome'>    
      <ul>
        {data.map((user) => 
          <li  className='user' key={user._id}>
            {user.Username}
          </li>  
        )}

      </ul>

      <h1>Welcome to GRM</h1> 
      <h1>Explore the music world</h1>

    </div>
   )
}

Unsurprisingly enough it was a matter of the right amount of brackets. Here's what my data retrieved from MongoDB looked like:

{"users":
[{
"_id":"622c6b2e1c9e40c9775a8940",
"Username":"222","Email":"[email protected]",
"Password":"$2b$10$OafBy/2M6a3TZOf/Fslv.u/7tREMGJk6BD.GCiul23giaYh58CTfC",
"Lists":[],"__v":0
},
{
"_id":"622c6b491c9e40c9775a8944",
"Username":"111","Email":"[email protected]",
"Password":"$2b$10$cpqiLxsW70stj/4P5AGKUucvXyRDha6Fy3bpGsz0vg.1p0ia.7Jwi",
"Lists":[],"__v":0
}
]}

Upvotes: 1

Peter
Peter

Reputation: 707

If users is an array, then you only need to pass users to setUsers

import React, { useState, useEffect } from "react";
import "./welcome.css";

function Welcome() {
  const [data, setUsers] = useState([]);

  useEffect(() => {
    fetch("http://localhost:4000/users")
      .then((res) => res.json())
      .then(({ users }) =>
        setUsers(users)
      );
  });

  return (
    <div className="welcome">
      <ul>
        {data.map((user) => (
          <li className="user" key={user._id}>
            {user.Username}
          </li>
        ))}
      </ul>

      <h1>Welcome to GRM</h1>
      <h1>Explore the music world</h1>
    </div>
  );
}

Upvotes: 1

Shehzad Ahmed
Shehzad Ahmed

Reputation: 11

Remove line

.then(users => setUsers({users}, console.log(users), console.log(data)))

Add This

.then ((res)=>{setUsers(res.data)})

I hope it will work for you

Upvotes: 1

Related Questions