-2
const [userDetail, setUserDetail] = useState([])

useEffect(() => {
    getUsersData()
}, [])

const getUsersData = async () => {
    const userResp = await MyService.getInstance().getEntities()

    let data = []
    console.log(userResp)

    if (userResp) {
        userResp.map((d) => {
            data.push({
                name: d.name,
                username: d.username
            })
        })
        
        setUserDetail(data) // < --------this line--------
        console.log(data)
    }

    console.log(userDetail)
}

setUserDetail doesnt set the value for userDetail Array even console.log(userDetail) shows empty array. like this:

Console shows this o/p

10 Rep
  • 2,217
  • 7
  • 19
  • 33

1 Answers1

0

Two things:

  1. You are using the .map method as .forEach. The purpose of the .map method is to return a new array transformed. Then, this data array is not necessary.If you want to transform an array, you can use a map, but is not necessary to create a new array. Map will return the new array transformed.
  const[ userDetail , setUserDetail ] = useState([])

  useEffect( () => {
    getUsersData()
  }, [])

  const getUsersData = async() =>{
    const userResp = await MyService.getInstance().getEntities()
    console.log(userResp)
    if(userResp){
     setUserDetail(
     userResp.map((d) => (
        {
          name:d.name,
          username:d.username
        })
     ))
    }
  }

 console.log(userDetail)
  1. Try to move your console.log outside the method getUsersData. Then you will see all values for userDetail after each render.