Reputation: 137
so what i'm trying to do is to use axios to fetch some data from a json file on the root of my project and display these data in a list. I must use the functionnal method and hooks.
So i've search how to use axios this way. I tried to integrate it but, in the end i did not manage to display the list. I dont really know whats'missing or what i do wrong?
import { useState, useEffect } from "react";
import axios from 'axios';
export default function Groundlist() {
const [groundNames, setgroundNames] = useState([]);
const [error, setError] = useState('');
const [isError, setIsError] = useState(false);
useEffect(() => {
const fetchData = () => {
axios
.get('./../../../UballersGroundsData.json')
.then((res) =>{ setgroundNames(res.data);})
.catch(err => { setIsError(!isError); setError({error}) })
}
fetchData()
}, []);
return(
<div>
<h1>Hello world!</h1>
<ul>
{groundNames.map((name, id) => (
<li key={id.groundId}>{name.groundName}</li>
))}
</ul>
</div>
)
}
A part of the .json file just to know the structure
{
"ground1":{
"groundId": "2",
"address": "77-101 Quai Branly, Paris, France",
"addressLanguage": "fr_FR",
"basketNumber": "4",
"city": "Paris",
"country": "France",
"gameType": "3x3,4x4,half,full",
"groundCreatorId": "1",
"groundDescription": "Il y a 2 terrains : 1 de basket et 1 citystade, (sur lequel il y a basket et foot sur le même terrain)",
"groundLevel": "advanced,semiPro,pro",
"groundName": "Bir-Hakeim",
"groundNumber": "2",
"groundPhoto": "P1190343.JPG",
"groundType": "concrete",
"idGround": "2",
"lastUpdate": "2018-10-07 21:17:07",
"latitude": "48.8564",
"limit": "public",
"longitude": "2.29074",
"multisport": "1",
"net": "2",
"price": "",
"roof": "1",
"status": "validated",
"transport": "RER C, station Champ de Mars - Tour Eiffel ; métro ligne 6, station Bir-Hakeim"
}
}
Thank you !
Upvotes: 0
Views: 1855
Reputation: 2102
I'm confused as to why you're using axios to do this. It seems more natural to import
the file and set it as your default value for groundNames (instead of the empty array you are using now).
Or just use the raw value, since your code doesn't ever modify the array.
Upvotes: 0
Reputation: 11
You can try adding import React, {useState, useEffect} from 'react
.
Upvotes: 1
Reputation: 79
Is there a specific reason you're using axios? You can do this using just the fetch module
https://www.pluralsight.com/guides/fetch-data-from-a-json-file-in-a-react-app
Upvotes: 0