skip to Main Content

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


  1. Chosen as BEST ANSWER

    GOT IT !!! ensure to add [router] (or your query parameter) as part of the effect dependencies.

    https://github.com/vercel/next.js/discussions/11484


  2. Before the api call finishes and teams is set teamX will be empty. In this case teamX[0] will be undefined. You can just access it with teamX[0]?.name or wrap the whole section where you show the team info with a conditional:

    { teamX[0] ? <section><h1>{teamX[0].name}</h1></section> : <section>Loading...</section> }
    
    Login or Signup to reply.
  3. forget the fetchdata function and and just use the axios inside the useEffect

    useEffect(()=>{]
    axios('/api/getTeam/data')
    .then(res=>setTeams(res.data)
    },[])
    

    and then render

    <h1>{teamX[0]?.name}</h1>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search