Collect the Data in React - veerleprins/frontend-applications GitHub Wiki
To be able to work with the datasets, they must first be loaded into the code. We do this by using fetch() within JavaScript.
To fetch data, I first started by literally copying my written code from the functional patterns course and pasting it into the App component:
import './App.css';
function App() {
async function fetchData(url) {
const response = await fetch(url);
return response.json();
}
const data = fetchData('https://opendata.rdw.nl/resource/b3us-f26s.json');
return (
<div className="App">
<Title title="The electric car in the Netherlands"/>
<div> { data } </div>
</div>
);
}
export default App;But I immediately got to see a very large error:
Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
And when I tried to console log my data, I saw the following:
Promise { <state>: "pending" }What I hadn't thought about was the fact that of course this would never work. Firstly, this is because I lacked a promise / async await (the response is an await but converting the response to a json file is also an await). In addition, I had to use the useState and useEffect hook to fetch the data here.
Then I started looking for a lot of examples online how you can best fetch data within react with hooks. Eventually I came across an example from reactgo.com in which they create their own 'hook' to fetch the data. I tried to use this to see if that would work in my code. Eventually with a lot of effort I got to see something on my screen with the help of this example. I got to see all data as objects (a json format but as a string). Below is my code of this:
My App component:
import './App.css';
import { useFetch } from './Components/Organisms/FetchingData';
function App() {
const data = useFetch();
if (!data) {
return <p>Loading...</p>;
}
console.log(data);
return <div>{JSON.stringify(data)}</div>
}
export default App;My useFetch hook / component:
import React, { useState, useEffect } from 'react';
import { API_1 } from '../../modules/helpers/utils';
export function useFetch () {
const [data, setData] = useState(() => {
return null;
});
useEffect(() => {
async function fetchData() {
let response = await fetch(API_1);
let json = await response.json();
setData(prevRes => json);
}
fetchData();
}, []);
return data;
}But now I had the question how to proceed with this. To load and use the data in this way did not seem like a good way to me. This is mainly because there should be an intermediate step: the process in which the data is cleaned up. The way I coded with this I wouldn't have a clue how to start cleaning the data.
For this reason, I decided to search further online for other examples of loading the data using hooks. Still, it was constantly not coming out quite the way I wanted so I decided to take a look at the work of other students. I also went to look at Victor's repository and see how he solved fetching the data. Based on his code, I suddenly saw how I could improve my code.
First I changed my App component file. Here I created all the states I needed for fetching and cleaning the data and also used the useEffect hook. I also created a number of new components that I could reuse. Below is my code:
import './App.css';
import { startText, secondText } from './modules/helpers/utils';
import { Title } from './Components/Atoms/Title';
import { Paragraph } from './Components/Atoms/Paragraph';
import { SubTitle } from './Components/Atoms/SubTitle';
import { useEffect, useState } from 'react';
import { fetchData } from './modules/fetchData';
function App() {
// Datasets:
const [parking, setParking] = useState(null);
const [cars, setCars] = useState(null);
const [electric, setElectric] = useState(null);
useEffect(() => {
fetchData(setParking, setCars, setElectric);
}, []);
if (!parking) {
return <div className="App">
<p>Loading...</p>
</div>
}
return <div className="App">
<Title/>
<Paragraph text={startText} name="firstP"/>
<SubTitle subtitle="Hoeveel elektrische auto’s rijden er in Nederland?"/>
<Paragraph text={secondText} name="secondP"/>
<div>{JSON.stringify(parking[0])}</div>
<SubTitle subtitle="Welke merken zijn het populairst in Nederland?"/>
<SubTitle subtitle="Waar staan de meeste laadpalen in Nederland?"/>
</div>
}
export default App;After this I changed my fetchData file. In the meantime I also loaded D3 so that I could fetch the data with it and use it as a json file. More about loading D3 can be read on this page: Wiki - Using D3 in React. Below is my code for the fetchData function:
import { json } from 'd3';
import { API_1, API_2, API_3, API_4, columnArr1, columnArr2 } from './helpers/utils';
// Code from https://github.com/BVictorB/frontend-applications/blob/master/src/helper/fetchData.js
export async function fetchData (setParking, setCars, setElectric) {
const specData = await json(API_1);
// const locData = await json(API_2);
const allCars = await json(API_3);
const electricCars = await json(API_4);
setParking(specData);
setCars(allCars);
setElectric(electricCars);
};This way I finally knew how to fetch the data and then clean it up before it shows up on the page. The cleaning of the data can be read on the page: Wiki - Cleaning the data in React.