Search code examples
jsonreactjsfetch

Using react to fetch one item from json


So I got this problem. I am trying to fetch a local json file from my project. The json file is stored in the src folder.

This is my json file

[
    {
      "name": "Sunsssset Beach",
      "email": "[email protected]",
      "image": "https://images.unsplash.com/photo-1439130490301-25e322d88054?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1489&q=80",
      "price": 85,
      "maxGuests": 18,
      "lat": 60.393388,
      "lng": 5.22872,
      "description": "Get ready for some amazing sunsets as you sip a cocktail and watch dolphins play in the harbour below.",
      "selfCatering": true,
      "createdAt": "2020-09-04T09:07:10.367Z",
      "id": "5f5203bedc17b0a4b302f211"
    },
    {
      "name": "The Hideaway",
      "email": "[email protected]",
      "image": "https://images.unsplash.com/photo-1551906993-c8b38a6ab201?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=666&q=80",
      "price": 70,
      "maxGuests": 2,
      "lat": 60.425168,
      "lng": 5.358141,
      "description": "This secluded wilderness cabin is the perfect spot for a restful and cosy getaway.",
      "selfCatering": true,
      "createdAt": "2020-09-04T09:07:10.370Z",
      "id": "5f5203bedc17b0a4b302f213"
    },
    {
      "name": "Rest Easy",
      "email": "[email protected]",
      "image": "https://images.unsplash.com/photo-1512552288940-3a300922a275?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=751&q=80",
      "price": 120,
      "maxGuests": 14,
      "lat": 60.396779,
      "lng": 5.235602,
      "description": "Need some time off from your busy life to relax and unwind? Choose Rest Easy for the complete relaxation experience you desire.",
      "selfCatering": false,
      "createdAt": "2020-09-04T09:07:10.370Z",
      "id": "5f5203bedc17b0a4b302f212"
    }
  ]

And here is my project file

function Establishment() {
  const [establishment, setEstablishment] = useState([]);
  const [loading, setLoading] = useState(true);

 useEffect(() => {
    fetch("jsonfile")
      .then((response) => {
        // check if response returns ok
        if (response.ok) {
          return response.json();
        } else {
          setErrorHandle(true);
        }
      })
      .then((data) => {
        setEstablishment(data);
      })
      .catch((err) => {
        console.log(err);
        setErrorHandle(true);
      })
      .finally(() => setLoading(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

Now I want to be able to press a button do display all of these items, and by clicking on one item, it should display only that item in a different page. How do I do that?

Let me know if there is anything else you need to solve this problem :)


Solution

  • Firstly if the JSON data is in a local in your file system then you do not need fetch or axios

    Why you did not use Axios or Fetch?

    Axios or Fetch use to get or post data into the server. In our case, we read on the local folder file so that we use map().

    Note: most important when using Axios and Fetch we need URL parameter compulsory

    Now what you are to do is:

    1. Firstly Import the file wherever you want to use:

    import data from "../static/data/myData.json";

    2. Now you want to map through that Json file:

    <div>
        {
            data.map(myData, index)=>{
            
                return <div key={myData.id}>
    
                    <h1>{myData.name}</h1>
                    <h3>{myData.email}</h3>
                </div>
    
    
            }
        }  
    </div>
    
    • So that is how you want to handle this situation obviously structuring the content the way you desire not with h1's and h3's like I did