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>
);
}
setmyAppointment()call turnsmyAppointmentinto an object, arrays use square brackets:[...]. You probably want.then(result => setmyAppointment([...myAppointment, result]));(useState()creates separate state variables; you don't use it likethis.setState()where you have to pass the key: reactjs.org/docs/hooks-state.html)setmyAppointment(result), since you don't have to append to an existing array