skip to Main Content

i am building a movie website with react and the problem is happening in usestate I think pls take a look

i was trying to have my search bar display some results but it did not and is showing error in console Cannot read properties of null (reading ‘map’)

// import axios from "axios";
import React, { useEffect, useState } from "react";
import lodu from "../../utils/lodu"
import { Link } from "react-router-dom";
function Topnav(){
    const[query,setquery]=useState("");
    const[searches,setsearches]=useState(null);
    const getSearches = async()=>{
        try {
         const {data} = await lodu.get(`/search/multi?query=${query}`); 
         setsearches(data.results)
        } catch (error) {
           console.log("error is ",error) 
        }
    }
   useEffect(()=>{
    getSearches();
   },[query])
return(<>
<div className="w-full h-[12vh] relative flex justify-center items-center">
<i class="text-zinc-400 text-3xl ri-search-2-line"></i>
    <input  onChange={(e)=>{setquery(e.target.value)}}  value={query} className="w-[50%] text-zinc-200 mx-10 p-3 text-xl outline-none bg-transparent border-none" type="text"placeholder="search anything?" />
   {query.length > 0 && (<i 
   onClick={()=>setquery("")}
    class="text-zinc-400 text-3xl ri-xrp-fill"></i>)}
    <div className="w-[50%] absolute max-h-[50vh] bg-zinc-200 top-[90%] overflow-auto">
        {searches.map((s,i)=>{ 
         return (<Link key={i} 
        className="hover:text-zinc-100 hover:bg-zinc-400 duration-200 font-semibold w-[100%] flex justify-start items-center p-8 bg-zinc-200 border-b-2">
          <img src="" alt="" />
          <span>hi</span>
          </Link>)
        })}
  
       
    </div>
</div>

</>)
}

export default Topnav

3

Answers


  1. On page load searches is set to null. Also on page load you’re mapping over searches.

    Try changing {searches.map((s,i)=>{ to {searches?.map((s,i)=>{

    Login or Signup to reply.
  2. update your useState default value to empty array.

    const[searches,setsearches]=useState([]);
    
    Login or Signup to reply.
  3. You can simply add a check if search result have some value then only map like this:

    {searches && searches.length > 0 && searches.map((s, i) => (
                            <Link key={i}
                                className="hover:text-zinc-100 hover:bg-zinc-400 duration-200 font-semibold w-[100%] flex justify-start items-center p-8 bg-zinc-200 border-b-2">
                                <img src="" alt="" />
                                <span>hi</span>
                            </Link>
                        )
                        )}
    

    and update default value of search as follows:

    const [searches, setsearches] = useState([]);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search