After fetching data from mongo, I encountered an issue where my useState([])
is initially defined as undefined
. Can someone please offer a solution to this problem?
const router = useRouter()
const {id} = router.query
console.log(id) // first undefined then team
const [teams, setTeams] = useState([])
const teamX = []
if(id === 'team') {
const x = teams.find(item => item._id === '64501115948ae9070cdd5ba5')
teamX.push(x)
}
console.log(teamX) // first [] then [{...}]
const fetchData = async () => {
try {
const { data } = await axios('/api/getTeam/data')
console.log(data) // (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
setTeams(data)
} catch (error) {
console.log(error)
}
}
useEffect(() => {
fetchData()
}, [])
When I checked the console logs, I found the following:
undefined // console.log(id)
[] // console.log(teamX)
team // console.log(id)
[undefined] // console.log(teamX)
(8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
team // console.log(id)
[{…}] // console.log(teamX)
If I attempt to access the data like this:
<h1>{teamX[0].name}
Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'name')