Home > database >  Why do i keep getting typeerror: not a function while trying to filter or map an array
Why do i keep getting typeerror: not a function while trying to filter or map an array

Time:10-14

So, I am trying to filter and map an array from the GIPHY api using stored variables in the useState hook.

Here's my code

   const [gifdata, setGifdata] = useState([])
   const [Search, setSearch] = useState("")

   function handleChange(e) {
       setSearch(e.target.value)
   }

useEffect(()=> {
    axios.get(`https://api.giphy.com/v1/gifs/trending?api_key=nKEFKPSILLeIlqLEjqhVsRO8ShxIjfcn&limit=50&rating=g`)
   .then(res=>{
       setGifdata(res.data)
       console.log(res.data)
   })
}, [])

const filteringSearch = gifdata.filter(gif=>
   gif.title.toLowerCase().includes(Search.toLowerCase()))

   return (
       <div>
           <header className="bg-blue-600">
               <div className="logo">
                   <label htmlFor="logo">DejareX</label>
               </div>
           </header>
           <div className="heroSection mx-auto">
               <h1>GIF Collections at it's peak</h1>
               <p>loremipsum blah blah blah</p>
           
                   <input type="text" placeholder="Search For A GIF" onChange = {handleChange} />

                   {filteringSearch.map(gif => {
                       return (
                           <Gif 
                           key = {gif.id} 
                           gifImgSrc = {gif.images.original.webp}
                           description = {gif.title}
                           />
                       )
                   })}
       </div>
       </div>
   )
}

NOTE: CREATED A RANDOMEMAIL ADDRESS TO GET THIS API KEY, Its not for production. I am new to react, please try put me through as easy as possible

Someone said the data from the api is probably not an array, i rechecked and it seems like it is true. Cause it first returns an object before getting into the array, who can help with fixing that please

CodePudding user response:

As I said, res.data is not an array. axios adds another data layer to the result. Therefore your res.data is not the same as you see in the browser, in fact it is:

{data: Array(50), pagination: Object, meta: Object}

Therefore, changing res.data to res.data.data will solve the issue

Here is a dummy Live Demo

  • Related