Home > Net >  I get 'undefined' when i try to fetch data from an API but when i access it again it works
I get 'undefined' when i try to fetch data from an API but when i access it again it works

Time:09-04

I'm developing a Tv shows website using https://api.themoviedb.org API. Here are the routes I set up :


 <>

    <Router>
     <Navbar/>
     <Routes>
     <Route path='/' element={<Home/>}/>
     <Route path='/signup' element={<Signup/>}/>
     <Route path='/movieOverview/:id' element={<MovieOverview/>}/>
     <Route path='*' element={<Error/>}/>
  </Routes>
</Router>
</>

In one of them i set a dynamic path prop on the Route component that renders the movieOverview component - <Route path="/movieOverview/:id" element={}

So I can use the useParams hook to get the ID when someone clicks on any of the shows to see more details navigate to to={/movieOverview/${props.id}}

Which is here:

export default function MovieOverview(){
    const [moviedetails, setMovieDetails] = React.useState()
    const {id} = useParams()

    React.useEffect(() => {
        getData()
        window.scrollTo(0,0)
    }, [])

    const getData = () => {
        fetch(`https://api.themoviedb.org/3/tv/${id}?api_key=172f725b29bb276f5c4b6e294a988fc5`)
        .then(res => res.json())
        .then(data => setMovieDetails(data))
    }
    return(
        <div className='overview-1'>
            <p className='detail'>{moviedetails.name}</p> 
        </div>
    )
}

The issue is the getData function returns 'undefined', but when I delete {moviedetails.name} and try it again, it delivers the data. i want it to deliver the data immediately.

CodePudding user response:

TL;DR

change your code as below:

  <p className="detail">{moviedetails?.name}</p>

Why my code is not working ?

Initially moviedetails is undefined , so when you are trying to access name property , it is throwing error. And once the API response is received the value is getting set , so you are able to read the name property.

Another way of solving it would to be initialize your state with empty object as below :

    const [moviedetails, setMovieDetails] = React.useState({})

Here is a working example : Demo

  • Related