Home > Net >  Reactjs - App.js:34 Uncaught TypeError: ch.map is not a function
Reactjs - App.js:34 Uncaught TypeError: ch.map is not a function

Time:12-24

I am getting ch.map is not a function error in my application.js file while I am doing a simple GET request from a Rest API:

function App() {

  const [ch, setCh] = useState([]);

   useEffect(()=>{

    fetch("https://localhost:12354/api/v1/Objects", {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Basic YWRt'
      }
    })
    .then( resp => resp.json())
    .then( resp => setCh(resp))
    .catch( error => console.log(error))


  }, [])

  return (
    <div className="App">
      <header className="App-header">
        <h1>Object Manager</h1>
      </header>
      <div className = 'layout'>
        <div> 
          { ch.map( i => {
            return <h2>{i.Name}</h2>
          })} 
          </div>
        <div> Object Details </div>
      </div> 
    </div>
  );
}

And here is the output for the same API call from postman. I am trying to get the "Name" in my above javascript:

{
    "@odata.context": "$metadata#Object",
    "value": [
        {
            "@odata.etag": "W/\"24979988a17d428c\"",
            "Name": "Load Actual",
            "StartTime": "2021-12-23T22:46:24 10:00",
            "DSTSensitive": true,
            "Active": true,
            "ExecutionMode": "MultipleCommit",
            "Frequency": "P1DT00H00M00S",
            "Attributes": {
                "Caption": "Load Actual"
            }
        }
    ]
}

CodePudding user response:

Change setCh(resp) to setCh(resp.value). When you call setCh(resp), you are setting ch to equal the whole response json. That means it is the map with the keys @odata.context and value. The method map does not exist on an object, but does on resp.value, which is an array.

  • Related