Search code examples
javascriptreactjsjsxmap-function

The state variable returned after using useState react hook shows .map is not a function


This code gives me error when I try to map the state variable returned after calling useEffect hook. On console, when I print the myAppointment it shows two values one is empty ([]) and other (Array[25]) I want to extract the petname values from this array . But getting error "map is not a function" Please look into it and help me!

function App() {
  const [myAppointment, setmyAppointment] = useState([])
  useEffect(() => {
      fetch('./data.json')
      .then(response=> response.json())
      .then(result=>{
        const apts=result.map(item=>{
          return item
        })
        setmyAppointment(state=>({...state,
          myAppointment:apts
        }))
      })**strong text**
  },[])

  console.log(myAppointment)
  const listItem = myAppointment.map((item)=>{
    return(
      <div>{item.petName}</div>
    )
  })

  return (
    <main className="page bg-white" id="petratings">
    <div className="container">
      <div className="row">
        <div className="col-md-12 bg-white">
          <div className="container">
            {/* {listItem} */}
            <div><AddAppointment /></div>
            <div><SearchAppointment /></div>
            <div><ListAppointment /></div>
          </div>
        </div>
      </div>
    </div>
  </main>
  );
}

Solution

  • You have you state as an array. However when you try to update it you convert it into an object with key myAppointment which is the cause of your error.

    You must update your state like

      setmyAppointment(state=> [...state, ...apts]);
    

    However since the state is initially empty and you only update it once in useEffect on initialLoad, you could also update it like

     setmyAppointment(apts);