Search code examples
javascriptreactjsbrowserfetchrendering

TypeError: state.confirmed.map is not a function


I try to fetch data from one API on Reacts. I tried every single possibility to render the data on browser but I don't know what I am doing wrong?

This is app.js

import React, { useState, useEffect } from "react";
import { stat } from "fs";

function App() {
  const [loading, setLoading] = useState(false);
  const [state, setstate] = useState({
    confirmed: "",
    recovered: "",
    death: ""
  });

  useEffect(() => {
    coronaData();
  }, []);
  const coronaData = async () => {
    setLoading(true);
    try {
      const response = await fetch(
        "https://w3qa5ydb4l.execute-api.eu-west-1.amazonaws.com/prod/finnishCoronaData"
      );
      const data = await response.json();
      console.log(data.confirmed);
      setstate({
        confirmed: data,
        recovered: data.recovered,
        death: data.death === null ? null : alert("Lucikily No-one died")
      });
    } catch (error) {
      console.log(error, "FAILED TO FETCH");
    }
    setLoading(false);
  };
  return (
    <div className="App">
      {state.confirmed.map(list => {
        return (
          <ul>
            <li>{list.healthCareDistrict}</li>
          </ul>
        );
      })}
    </div>
  );
}

export default App;

**Ignore this message, In order to post this question, I need to write more. **


Solution

  • The reason is you are using an empty string as default value for state.confirmed in useState(). Technically .map() can be used on arrays only that caused the error because the app tried to call on an empty string.

    I would change to an [] when initially defining:

    const [state, setstate] = useState({
        confirmed: [],
        recovered: "",
        death: ""
      });
    

    I believe this change also applies for recovered as well later. Currently you are not using in your code as it seems.

    I hope this helps!