Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
  );
}
like image 691
Gazal Jain Avatar asked Jun 17 '26 12:06

Gazal Jain


1 Answers

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);
like image 111
Shubham Khatri Avatar answered Jun 19 '26 03:06

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!