Fetch Data from a local JSON file in react js (in functional component)
It is a simple tutorial to fetch data from a local JSON file
2 min readMay 31, 2021
The requirements and good architecture for this functionality will be:
|-node_modules
|-public
|-data.json (our json file)
|-src
|-components (it is going to contain the components)
|-hooks (custom hook which will fetch by calling util function)
|-utils (the js function which will fetch data)
|-app.js
JSON File:
public/data.json
{"persons": [
{ "name":"Archana", "age": "21" }, { "name":"Shelly", "age": "25" }, { "name":"Pranjal", "age": "30", }
]
}
This JSON file will be placed in the public folder.
util file:
utils/get-data.js
export const getData = async (filePath, fileType) => {
try{
const response = await fetch(filePath);
switch (fileType.toUpperCase()) {
case 'JSON':
return response.json();
default:
return response;
}
} catch (error) {
return error;
}
}
We can give filePath and fileType a value like this:
filePath="path of json file", fileType="file type here"
Custom Hook file:
hooks/customHook.js
import { useState, useEffect } from 'react';
import { getData } from '../utils';export function customHook(){
const [data, setData] = useState();
useEffect(()=>{
fetchData();
},[]) const fetchData = async () => {
try {
const response = await getData('data.json', 'json');
setData(response.persons);
} catch (error) {
console.error(error);
}
};
return(data);
}
In the useEffect above, we are using it like CoponentDidMount
lifecycle method of class components by giving it the second parameter of an empty array.
Components File:
components/jsonFetch.js
import React from 'react'
import customHook from '../hooks/customHook'
import Person from './Person'function JsonFetch() {
const {data} = customHook()
const PersonList = data.map(person => <Person person={person}/>)
return <div>{PersonList}</div>;
}export default JsonFetch;components/person.js
import React from 'react';const Person = ({person}) =>{
return(
<div>
<h1>Name: {person.name}</h1>
<h3>Age: {person.age}</h3>
</div>
)
}
Result:
Thank you for reading!
Please leave comments if you have any suggestion/s or would like to add a point/s or if you noticed any mistakes/typos!
P.S. If you found this article helpful, clap! ๐๐๐ [feels rewarding and gives the motivation to continue my writing].