Search code examples
javascriptreactjsreact-nativejavascript-objectsreact-map-gl

Map function is throwing errors in react js


I am new to React js and learnt developing static websites very quickly. Since i was a huge fan of python i have developed my backend using Django-rest-framework.

i am successfully fetching my data from backend with react front end.

how ever i always like to work with functional components than state components. i know i need to map my state object inorder to display contents in it but it is raising an error

TypeError: users.map is not a function

i don't know why and please guide me through this. one important thing is i am perfectly logging my data to console but not inside return().

the following is my code

import React,{useState,useEffect} from "react"
import{useHttpClient} from './components/http-hook'

const App=()=>{
  const[users,setuser]=useState({})
  const{isLoading,error,sendRequest,clearError}=useHttpClient()


  useEffect(() => {
    const fetchUsers=async()=>{
      try{
        const responseData=await sendRequest("http://127.0.0.1:8000/backend/list/")
        setuser(responseData)
      }
      catch(err){console.log(err)}
    }
   fetchUsers()
  }, [sendRequest])

  const fetchUserslist=async=>{
    console.log(users)
  }

    return(<div>
      <button onClick={fetchUserslist}>See list</button>
      <ul>
    {users.map(user=><div>{user.name}</div>)}
      </ul>
      </div>

    )
}

export default App

i have created my own custom hook useHttpClient to handle data and no complaints about it


Solution

  • As i see

    const[users, setuser]=useState({})
    

    you have initiated users to a object it's not an array so when we try to users.map it will ended up with above error

    to perform .map operation it has to be initialize to an array as below

    const[users,setuser]=useState([])
    

    if you really want to iterate through the object, the best thing you can do is get and array out of the object and loop it for ex:

    const obj = {name: "hello", age: 23};
    
    Object.keys(obj).map((key) => <div>{obj[key]}</div>)