-1

So, im fetching data from an api and when i console log the response im able to see the api as expected. Im storing the data in states but whenever i want to iterate the state to return the data in the screen i get the map undefined error. I have tried evrything i found here but nothing works. Please help me with this. Thank you

...
const [state, setState] = useState([]);
  let headers = new Headers();
  headers.set("Authorization", "Basic " + btoa(username + ":" + password));

  useEffect(() => {
    getData();
  }, []);

  const getData = async () => {
    const a = await fetch(url, { method: "GET", headers: headers });
    const response = await a.json();
    setState(response);
    console.log(response);
  };
  // console.log(state)

  return (
    <div>
      {state.data.map((test) => (
        <div>
          <p>{test.place}</p>
        </div>
      ))}
    </div>
  );
};

export default FetchApi;


api

{
    "data": [
        {
            "type": "Other",
            "place": "US",
            "attributes": [
                {
                    "displayName": "name",
                    "value": "Jenna"
                },
                {
                    "displayName": "Gender",
                    "value": "Female"
                },
                {
                    "displayName": "Phone_number",
                    "value": "+12346543"
                }
            ]
        }
        
    ]
}
Rowan Frank
  • 117
  • 6

1 Answers1

0

You are using the raw response, so first

// change this
const [state, setState] = useState([]);

// to this
const [state, setState] = useState({});

because in the first render, state.data is undefined, so make sure to handle that case

return (
  <div>
    {(state.data || []).map((test) => (
      <div>
        <p>{test.place}</p>
      </div>
    ))}
  </div>
);
hgb123
  • 13,869
  • 3
  • 20
  • 38