Gazal Jain
Gazal Jain

Reputation: 49

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

Upvotes: 3

Views: 478

Answers (2)

Suraj Auwal
Suraj Auwal

Reputation: 318

The problem is from the way you're setting your state after the data is fetched.

You're setting the state as an object by instead of an array.

Let's Take a look at the line where you set the state.

setmyAppointment(state=>({...state,
          myAppointment:apts
        }))

Using the spread operator with curly braces tells JavaScript compiler to spread an object, and obviously that's not what you want.

What you ought to do is instead of curly braces, use square brackets. That will tell the compiler you want to spread an array.

So it should be something like this .


setmyAppointment(state=>([...state
        ]))

And if I were you, I will do this a little bit different. I will set the state like this

setmyAppointment(apt)

I hope this helps

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 282150

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

Upvotes: 1

Related Questions