I fetched data from mongo, but before I can get data my useState([])
define as undefined
.
Can you please tell me how to fix this problem?
const router = useRouter()
const {id} = router.query
console.log(id) // first nudefined 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()
}, [])
my console.log()
show me this:
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 access data :
<h1>{teamX[0].name}
Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'name')
3
Answers
GOT IT !!! ensure to add [router] (or your query parameter) as part of the effect dependencies.
https://github.com/vercel/next.js/discussions/11484
Before the api call finishes and teams is set
teamX
will be empty. In this caseteamX[0]
will be undefined. You can just access it withteamX[0]?.name
or wrap the whole section where you show the team info with a conditional:forget the fetchdata function and and just use the axios inside the useEffect
and then render