Home > database >  "TypeError: status.map is not a function" - TypeScript using useState & Map
"TypeError: status.map is not a function" - TypeScript using useState & Map

Time:10-05

I'm trying to understand why I'm having this Error on TS, when I write a letter on input an error popup "TypeError: status.map is not a function", is my first time using TS.

this is my original code on github -> https://github1s.com/SantGT5/Front-JW/blob/dev/src/Component/Search.tsx

this is where the error is ->

interface foundUser {
  name?: any;
  map?: any;
}

const [status, setStatus] = useState<foundUser>([]);

  useEffect(() => {
    async function fetchSearch() {
      try {
        const response: any = await api.post("/search", { name: status.name });

        setStatus({ ...response.data });
      } catch (err: any) {
        console.log(err.response);
      }
    }
    fetchSearch();
  }, [status.name]);
  
  
        <ol>
        {status.map((elem: any) => {

          <li>{elem.name}</li>

        })}
      </ol>

And, is correct to say interface -> map?: any ?

CodePudding user response:

setStatus({ ...response.data });

You are settings it as an object with response.data inside.
You can't map through an object, only arrays.

  • Edit:
    You actually can loop through objects, but it's done differently.
    Check this out if relevant.
  • Related