Home > Software design >  React with fetch api data show in console but don't retrieve
React with fetch api data show in console but don't retrieve

Time:10-20

With Fetch API and useState, I try to fetch data from TMDB. After writing some code data is shown in the console correctly but can't retrieve.

import React, { useState, useEffect } from 'react'
import MovieCard from '../components/MovieCard'
import { TrendingMovie } from '../components/Config'

export default function Trending() {
   const [trendingList, setTrendingList] = useState([])

   useEffect(() => {
      const fetchData = async () => {
         let res = await fetch(TrendingMovie(1))
         let data = await res.json()
         setTrendingList(data.results)
      }

      fetchData()

   }, [])

console.log(trendingList)

return (
  <div>
    {trendingList && trendingList[0]?.adult}
</div>
)}

enter image description here

CodePudding user response:

Well, adult has the value of false and booleans do not render by default in React.

You can render boolean values by first converting them to strings: String(trendingList[0]?.adult).

So instead you could do:

return (
  <div>
    {trendingList && String(trendingList[0]?.adult)}
  </div>
)

CodePudding user response:

with:

{TrendingMovie && TrendingMovie[0]?.adult}

You are tellig your code to render TrendingMovie[0]?.adult if your state value is true.

Try:

{TrendingMovie[0]?.adult && TrendingMovie}

CodePudding user response:

I guess you are rendering it wrong. You are console logging trendingList and rendering component TredingMovie

Try this

return <div>{trendingList && trendingList[0]?.adult}</div>;

CodePudding user response:

After using this code app work correctly

    const fetchData = async () => {
  try {
        let res = await fetch(TrendingMovie(1))
        let data = res.json().then(({ results }) => setTrendingList(results))
       } catch (error) {
        console.log('error', error)
  }
  
}
  • Related