How to fetch API in React

To fetch data from an API in React, you can use the built-in fetch() function, which is built into modern web browsers. fetch() allows you to make a request to an API and receive a response in JavaScript format or you can use a library like Axios or jQuery. Here's an example using the fetch() function:

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In this example, we're making a GET request to the JSONPlaceholder API and fetching some data. The fetch() function returns a promise that resolves with a response object. We're using the .then() method to handle the response object and convert it to JSON format using the .json() method. We're then logging the data to the console.

Note that fetch() is asynchronous, which means that it doesn't block the main thread of your application while it's waiting for the response. This is important in React, because it allows the app to keep running and rendering other parts of the UI while the data is being fetched in the background.

In a real-world application, you'll likely want to store the fetched data in a component's state, so that it can be displayed in the UI. To do this, you can use the useState and useEffect hooks, like this:

import React, { useState, useEffect } from 'react';

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(data => setData(data))
      .catch(error => console.error(error));
  }, []);

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {data.map(post => (
          <li key={post.id}>
            <h2>{post.title}</h2>
            <p>{post.body}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

In this example, we're using the useState and useEffect hooks to manage state and fetch the data when the component mounts. We're storing the fetched data in the data state variable and rendering it in the UI using the .map() method. Note that we're passing an empty array as the second argument to useEffect(), which means that the effect should only run once, when the component mounts.

Difference between Asynchronous and Synchronous function

The difference between synchronous and asynchronous is related to how an operation is executed or how the control flow is managed in a program.

In synchronous programming, the program execution happens in a sequential and blocking manner. This means that each operation in the program must be completed before the next one can begin. In other words, the program execution is halted until an operation completes, and only then does the next operation execute.

Here's an example of synchronous code:

function synchronousFunction() {
  console.log("Step 1");
  console.log("Step 2");
  console.log("Step 3");
}


synchronousFunction();

In this example, the synchronousFunction executes the console.log statements one at a time, in a sequential order. The output will be:

Step 1
Step 2
Step 3

On the other hand, in asynchronous programming, the program execution can continue without waiting for an operation to complete. Instead, the program initiates an operation and continues to execute other code while waiting for the operation to complete. Once the operation is complete, a callback function is called with the results.

Here's an example of asynchronous code using a callback function:

function asynchronousFunction(callback) {
  console.log("Step 1");
  setTimeout(() => {
    console.log("Step 2");
    callback();
  }, 1000);
  console.log("Step 3");
}

asynchronousFunction(() => {
  console.log("Done!");
});

In this example, the asynchronousFunction initiates a setTimeout function with a delay of 1 second. While waiting for the setTimeout function to complete, the program continues to execute the console.log statement for "Step 3". Once the setTimeout function completes after 1 second, it executes the console.log statement for "Step 2" and the callback function that logs "Done!" is called. The output will be:

Step 1
Step 3
Step 2
Done!

In summary, synchronous programming blocks the program until each operation completes, while asynchronous programming allows the program to continue executing while waiting for operations to complete, using callbacks or promises to handle the results.