How to fetch data in React using API or JSON

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for both humans to read and write, and for machines to parse and generate. It’s widely used in web applications for transmitting data between a server and a client as text. Though it originates from JavaScript, it is language-independent, meaning it can be used with most programming languages.

Key Features of JSON:

  1. Simple Structure: JSON is built from two main structures:
    • Objects: A collection of key/value pairs, similar to a dictionary or hash map in other languages. Keys are strings, and values can be strings, numbers, arrays, booleans, objects, or null.
    • Arrays: An ordered list of values (which can be strings, numbers, objects, etc.).

JSON Syntax:

  • Object: Encased in curly braces {}, key-value pairs separated by colons :, and pairs are separated by commas ,.
  • Array: Encased in square brackets [], with values separated by commas.

Example of JSON:

{
  "name": "Alice",
  "age": 25,
  "email": "alice@example.com",
  "isStudent": false,
  "skills": ["JavaScript", "Python", "HTML"],
  "address": {
    "street": "123 Main St",
    "city": "Wonderland",
    "postalCode": "12345"
  }
}

Breakdown of the Example:

  • "name": "Alice" – A key (name) paired with a string value (Alice).
  • "age": 25 – A key (age) paired with a numeric value (25).
  • "isStudent": false – A key (isStudent) paired with a boolean value (false).
  • "skills": ["JavaScript", "Python", "HTML"] – A key (skills) paired with an array of strings.
  • "address": { ... } – A nested object (address) with its own set of key-value pairs (street, city, postalCode).

Two main uses of JSON:

  • Data Exchange: JSON is primarily used to transfer data between a client (like a web browser) and a server. For example, when an API is called, the server often responds with JSON data.
  • Configuration Files: JSON is used in configuration files for applications and services (e.g., package.json for Node.js projects).

JSON has become a standard format for data interchange due to its simplicity and compatibility across different programming languages and platforms.

Key Differences between JSON and JavaScript Object:

FeatureJSONJavaScript Object
TypeAlways a string (text format)Part of JavaScript code (live data structure)
Key FormattingKeys must be strings in double quotesKeys can be unquoted (except for special chars)
Allowed Data TypesStrings, numbers, booleans, arrays, objects, nullFunctions, undefined, and complex types allowed
Use CaseData exchange (API responses, file storage)Direct manipulation within a JS program
ConversionMust be parsed to be used in JavaScriptNo conversion needed

Example of creating a JavaScript object and adding a new property

const person = {
  name: "Alice",
  age: 25,
  email: "alice@example.com"
};

// Add a new property to the JavaScript object
person.isStudent = false;
console.log(person);  // Outputs: {name: "Alice", age: 25, email: "alice@example.com", isStudent: false}

Example of Converting JavaScript Object to JSON:

const person = {
  name: "Alice",
  age: 25,
  email: "alice@example.com"
};

const jsonString = JSON.stringify(person);  // Converts to JSON string
console.log(jsonString);  // Outputs: '{"name":"Alice","age":25,"email":"alice@example.com"}'

Example of Converting JSON to JavaScript Object:

const jsonString = '{"name": "Alice", "age": 25, "email": "alice@example.com"}';

const person = JSON.parse(jsonString);  // Converts JSON string to JavaScript object
console.log(person.name);  // Outputs: Alice

Here, I’ll explain two methods for fetching data in React.

Method 1. Using Fetch command to fetch data(for both API and JSON files)

Add this code to the component where you want to fetch the data. For a small application, you can use App.jsx (the parent component) to fetch data.

  const [myData, setMyData] = useState([]);

  useEffect(() => {
    fetch('https://api.example.com')
      .then(response => response.json()) //return a Java script object Promise. If you are expecting a text, use the response.text() 
      .then(result => {
        setMyData(result);
      })
      .catch(error => console.error('Error fetching data:', error));
  }, []);  // using empty dependency [] ensures the fetch only occurs once when the components renders

You should replace the API URL in line 4 with a valid address. Line 1 defines a component state to store the fetched data, so you can access the data using myData. You can choose any other name that you want for myData.

To fetch data from a JSON file using the fetch command, follow these steps:

  • Copy your JSON file to the ‘public’ folder in your project.
  • Change line 4 in the code to :
    • fetch('/myFile.json') // Replace 'myFile.json' with your actual file name.

Method 2. Direct import (only for JSON files)

“Additionally, you can directly import JSON files into your components. Copy your JSON file into the ‘src’ folder of your project or any of its subfolders, and then use the import command. For example, if your file is named ‘myfile.json’ and is located in the ‘public’ folder, the import command would look like this:

import myData from './myfile.json'; // Replace the filename ('myfile.json') and data object ('myData') with your preferred choices.

Once imported, the JSON file seamlessly transforms into an object (in this example, ‘myData’), ready for immediate use within your component.

Please note that in these examples, it is assumed that you have copied your file directly into the ‘src’ folder. If you place your file in a different directory, you should adjust the import path accordingly. For instance, if you copy your file to ‘src/data’ folder, refer to it in your code using './data/myfile.json' as the import path

Scroll to Top