Search code examples
javascriptreactjsapiaxiosuse-effect

TypeError: provinsi.map is not a function


    import React, { useEffect,useState } from "react";
import Box from "../Component/Box/";
import "../Component/Box/Box.css";
import axios from 'axios';

const Global = () => {
        const [provinsi,setProvinsi] = useState([]);
    
        useEffect(() => {
        axios
            .get("https://indonesia-covid-19.mathdro.id/api/provinsi")
            .then((response) => setProvinsi(response.data));
        }, []);
    
        return(
            <>
            {provinsi.map((item) => {
                return(
                    <Box 
                    kodeProvi={item.kodeProvi} 
                    kasusPosi={item.kasusPosi} 
                    kasusSemb={item.kasusSemb} 
                    kasusMeni={item.kasusMeni}
                 />
                );
            })}
        </>
        );
    };
export default Global;

-- And the API is--

{
"data": [{
    "fid": 11,
    "kodeProvi": 31,
    "provinsi": "DKI Jakarta",
    "kasusPosi": 145427,
    "kasusSemb": 130977,
    "kasusMeni": 2825
}, {
    "fid": 15,
    "kodeProvi": 35,
    "provinsi": "Jawa Timur",
    "kasusPosi": 65557,
    "kasusSemb": 57210,
    "kasusMeni": 4618

-- Can someone help me, why I get the provinsi.map is not function ? Thanks a lot. I allready console.log provinsi and I can see the array in the console, but when I try to show it, that was not function. I just new to learn react.JS, and somethin new for my project, thank you for help..


Solution

  • the error in this line:

     axios
            .get("https://indonesia-covid-19.mathdro.id/api/provinsi")
            .then((response) => setProvinsi(response.data));   //response.data `data` here is property of axios `response` object
    

    use this line:

     axios
            .get("https://indonesia-covid-19.mathdro.id/api/provinsi")
            .then((response) => setProvinsi(response.data.data)); // this is the actual data