In this guide, you’ll learn how to save and read the local JSON file in the react project.
Three ways of accessing the local JSON file. How to read JSON file using react API call(fetch, axios). JSON data in the js file.
Consuming Local JSON Data Using Fetch API
Inside src (No Need Axios or Fetch for api call). Save your JSON file inside src anywhere for example —.
then import and read inside any component like below.
State-Try to assign and handle through the state because state is dynamic, it enables a component to keep track of changing information in between renders and for it to be dynamic and interactive.
For the class-based component —.
Loading Data into the Component
How to read JSON file using reactjs API call(fetch, axios). Sometimes we need to test something locally so many times that’s why needed fake data instead of calling the API.
If your JSON data is in a public folder which is outside of src.
and you want to make an API call.
- public -> data.json. Note- For class-based component make API call insidecomponentDidMount lifecycle method.
- import and read like —. Complete code- https://github.com/akhtarvahid/local-json-react.git.
Thanks for reading and stay tuned!
Demo And Code Here
Creating API mockups for local testing and development allows you to work in a faster development environment.
One way to implement an API mockup is to copy the JSON data to a local file in your project directory and make your fetch or GET calls to that file instead of the real database.
As fetching data from an external source is still an asynchronous task, there are a number of errors you can run into while loading data from a JSON file.
- This guide will demonstrate how to correctly fetch data from a JSON file in your React app and consume it on the frontend.
- In a blank Create React App project, create a local JSON file named data.json inside the public directory. Your Fetch API calls made from a React component always looks for files or any other relevant assets inside this public directory.
- Create-React-App doesn't put your assets automatically inside this directory during compilation so you have to do this manually.