Search code examples
htmlreactjsfetchstrapi

Why am i only seeing "id" in my react app when the fetch get all the data from Strapi?


i am trying Strapi for the first time, and i cant put my raw data into my divs.

On Strapi everything is published, and for the public the get and getOne is checked. This way i can only see the "id" nothing else.

Any guess?

here is my result from fetch: data from fetch

Here is the code that i got from the tutorial page:

import { useEffect, useState } from 'react';
import "./App.css"
// Parses the JSON returned by a network request
const parseJSON = (resp) => (resp.json ? resp.json() : resp);

// Checks if a network request came back fine, and throws an error if not
const checkStatus = (resp) => {
  if (resp.status >= 200 && resp.status < 300) {
    return resp;
  }

  return parseJSON(resp).then(resp => {
    throw resp;
  });
};

const App = () => {
  const [error, setError] = useState(null);
  const [restaurants, setRestaurants] = useState([]);

  useEffect(() => {
    fetch('http://localhost:1337/api/restaurants', { headers:{ 'Content-Type': 'application/json' }, 
      method: 'GET' })
      .then(checkStatus)
      .then(parseJSON)
      .then(({ data }) => setRestaurants(data))
      .catch((error) => setError(error))
  }, [])

  if (error) {
    // Print errors if any
    return <div>An error occured: {error.message}</div>;
  }
  return (
    <div>
      <div>
        {restaurants.map(({ id, name, description }) => (
        <div className="black" key={id}>
          {name}
          {description}
          {id}
          </div>
          
          ))}
      </div>
    </div>
  );
};

export default App;

Solution

  • I figured it out forom Google.

    The map section needs to be changed to this:

    {restaurants && restaurants.map((restaurant) => (
            <div className="black" key={restaurant.id}>
              {restaurant.attributes.name}
              {restaurant.attributes.description}
              {restaurant.id}
              {restaurant.attributes.publishedAt}
              </div>
              ))}