Manasseh Codes
Manasseh Codes

Reputation: 125

How to Map Strapi API Data in React JS

I am trying to map the Data from a Strapi Headerless CMS API in my react application. I keep on failing. When I consoleLog I do see the data. But when I use the map function to display some out put on my return. There is no data being shown. I would need help.

export default function App() {

  const [Alldata, setAlldata] = useState([]);
  useEffect(() => {
    // GET request using fetch inside useEffect React hook
    fetch("http://localhost:1337/api/rows/")
      .then((response) => response.json())
      .then((json) => setAlldata(json));
    // empty dependency array means this effect will only run once (like componentDidMount in classes)
  }, []);

  console.log(Alldata);


  return (
    <div>{Alldata.map( data => 
      <p >{Alldata.Alldata.data.attributes.Country}</p>
      )}
      
      </div>
  )
}

This is what my API data looks like. I am able to see this data from postman and it is what I want to map and display all the items as a list.

{
    "data": [
        {
            "id": 1,
            "attributes": {
                "Description": "Hello Stu",
                "Vendor": "Sony Play Station",
                "VendorId": 20,
                "FaceValue": 50,
                "DefaultCost": 50,
                "ProductCode": 317,
                "Name": 50,
                "ProductCodeAlt": "FLASH-317",
                "ProductTypeEnum": "Wallet Top Up",
                "ProductStatusEnum": "Active",
                "CountryId": 179,
                "Country": "South Africa",
                "CountryAlpha2Code": "27",
                "Logo": "https://prod.za.flashcontentmanager.flash-infra.cloud/image/i955.png",
                "createdAt": "2022-05-03T12:08:43.718Z",
                "updatedAt": "2022-05-04T09:55:47.328Z",
                "publishedAt": "2022-05-03T12:08:47.100Z"
            }
        },
        {
            "id": 2,
            "attributes": {
                "Description": "R1 - R2500 1Voucher Token",
                "Vendor": "1 Voucher",
                "VendorId": 9,
                "FaceValue": 0,
                "DefaultCost": 0,
                "ProductCode": 311,
                "Name": null,
                "ProductCodeAlt": "FLASH-311",
                "ProductTypeEnum": "Token",
                "ProductStatusEnum": "Active",
                "CountryId": 179,
                "Country": "South Africa",
                "CountryAlpha2Code": "27",
                "Logo": "https://prod.za.flashcontentmanager.flash-infra.cloud/image/i910.png",
                "createdAt": "2022-05-03T12:29:58.102Z",
                "updatedAt": "2022-05-03T12:30:00.609Z",
                "publishedAt": "2022-05-03T12:30:00.607Z"
            }
        },
        {
            "id": 3,
            "attributes": {
                "Description": "Refund 1Voucher Token",
                "Vendor": "1 Voucher",
                "VendorId": 9,
                "FaceValue": 0,
                "DefaultCost": 0,
                "ProductCode": 392,
                "Name": null,
                "ProductCodeAlt": "FLASH-392",
                "ProductTypeEnum": "Token",
                "ProductStatusEnum": "Active",
                "CountryId": 179,
                "Country": "South Africa",
                "CountryAlpha2Code": "27",
                "Logo": "https://prod.za.flashcontentmanager.flash-infra.cloud/image/i910.png",
                "createdAt": "2022-05-03T12:33:12.421Z",
                "updatedAt": "2022-05-03T12:33:14.089Z",
                "publishedAt": "2022-05-03T12:33:14.087Z"
            }
        }
    ],
    "meta": {
        "pagination": {
            "page": 1,
            "pageSize": 25,
            "pageCount": 1,
            "total": 3
        }
    }
}

Upvotes: 1

Views: 1563

Answers (2)

natalia
natalia

Reputation: 1

I am having very similar issue. Can't get to the attributes object. I tried both solutions but somehow it is not working. I need to display what I have in the attributes object...

 const [exercises, setExercises] = useState([]);



 const fetchApi = async () => {
    await fetch("http://localhost:1337/api/someApi")
      .then((response) => response.json())
      .then((exercise) => setExercises(exercise.data))
      });
  };

And after that I am maping

<div>
    {exercises.map((exercise) => {
      return <p key={exercise.id}>{exercise.attributes.Description}</p>;
    })}
  </div>

The API schema looks like that:

  {
  "data": [
    {
      "id": 1,
      "attributes": {
        "Desctiption": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
        "Type": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
        "ExerciseNo": 1,
        "createdAt": "2023-01-14T17:59:37.543Z",
        "updatedAt": "2023-01-14T17:59:39.806Z",
        "publishedAt": "2023-01-14T17:59:39.799Z"
      }
    },
    {
      "id": 2,
      "attributes": {
        "Desctiption": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
        "Type": "Duis aute irure dolor in reprehenderit in voluptate velit",
        "ExerciseNo": 2,
        "createdAt": "2023-01-14T18:00:32.365Z",
        "updatedAt": "2023-01-14T18:00:33.578Z",
        "publishedAt": "2023-01-14T18:00:33.571Z"
      }
    },
  ],
  }
}

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 203408

The AllData state will be an object with a data property that is the array, and then each element has the attributes.Country property.

Example:

export default function App() {
  const [Alldata, setAlldata] = useState({}); // <-- object

  useEffect(() => {
    // GET request using fetch inside useEffect React hook
    fetch("http://localhost:1337/api/rows/")
      .then((response) => response.json())
      .then((json) => setAlldata(json));
  }, []);

  console.log(Alldata);

  return (
    <div>
      {Alldata.data?.map(data => // <-- map Alldata.data, use a null check
        <p>{data.attributes.Country}</p>
      )}
    </div>
  );
}

Suggestion if you want to keep the Alldata state an array.

export default function App() {
  const [Alldata, setAlldata] = useState([]); // <-- array

  useEffect(() => {
    // GET request using fetch inside useEffect React hook
    fetch("http://localhost:1337/api/rows/")
      .then((response) => response.json())
      .then(({ data }) => setAlldata(data)); // <-- save the data array
  }, []);

  console.log(Alldata);

  return (
    <div>
      {Alldata.map(data => // <-- map Alldata array
        <p>{data.attributes.Country}</p>
      )}
    </div>
  );
}

Upvotes: 3

Related Questions