Home > Enterprise >  fetching data with useState and useEffect in react.js
fetching data with useState and useEffect in react.js

Time:03-11

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>
  )
}


CodePudding user response:

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>
  );
}

CodePudding user response:

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

  • Related