Home > Net >  Why am I unable to map this array of objects when it is loaded in useState()?
Why am I unable to map this array of objects when it is loaded in useState()?

Time:10-09

learning React but I'm trying to map an array of objects in a dropdown box.

I'm getting a "Uncaught TypeError: ids.map is not a function".

Why am I getting this error when I have set the loadedIds I get from the GET request into useState's setIds?

https://jsfiddle.net/4jh9c6dv/53/

Thank you for helping a beginner :')

function Dropdown ()
{
    const [ids, setIds] = React.useState([]);

 React.useEffect(() => {
    request.get(endpointIds).then((response) => {
      setIds(response.data);
      
      const loadedIds = [];
      
      for (const id in response)
      {
        loadedIds.push({
        id: ids,
        });
      }
      
      setIds(loadedIds);
      
    });
  }, []);
  
  
 const idsList = ids.map((id) => 
 (
        <option>id</option>
 ));

CodePudding user response:

You do not need to use setIds(response.data);. Remove that. response.data is not an array, response.data.ids is. That is why you get the error.

CodePudding user response:

response.data should be response.data.id you also forgot curly braces {id}

  • Related