Enhance Your JavaScript Applications with isomorphic-unfetch for Seamless Data Fetching

Introduction to Isomorphic Unfetch: A Lightweight Fetching Library

Isomorphic Unfetch is a minimalistic library that serves as a lightweight alternative to the standard Fetch API. It allows you to make HTTP requests across different environments, including browsers and Node.js applications. In this blog post, we will introduce you to the basics of isomorphic-unfetch along with several useful APIs and examples.

Why Use Isomorphic Unfetch?

Using isomorphic-unfetch ensures that you have a single codebase that works in both client and server environments. This is especially useful for universal (isomorphic) applications built with frameworks like Next.js.

Installation

npm install isomorphic-unfetch

Basic Usage

The basic usage of isomorphic-unfetch is similar to the Fetch API:

import fetch from 'isomorphic-unfetch';
async function fetchData() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');
  const data = await res.json();
  console.log(data);
}
fetchData();

Handling Different HTTP Methods

With isomorphic-unfetch, you can make different types of HTTP requests such as GET, POST, PUT, DELETE, etc. Here’s how you can do it:

GET Request

import fetch from 'isomorphic-unfetch';
async function getPosts() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');
  const data = await res.json();
  console.log(data);
}
getPosts();

POST Request

import fetch from 'isomorphic-unfetch';
async function createPost() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ title: 'foo', body: 'bar', userId: 1 })
  });
  const data = await res.json();
  console.log(data);
}
createPost();

PUT Request

import fetch from 'isomorphic-unfetch';
async function updatePost(id) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ title: 'foo updated', body: 'bar updated', userId: 1 })
  });
  const data = await res.json();
  console.log(data);
}
updatePost(1);

DELETE Request

import fetch from 'isomorphic-unfetch';
async function deletePost(id) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
    method: 'DELETE'
  });
  console.log('Post deleted:', res.status === 200);
}
deletePost(1);

Error Handling

It’s important to handle errors effectively in production applications. Here’s an example of how you can handle errors:

import fetch from 'isomorphic-unfetch';
async function fetchWithErrorHandling(url) {
  try {
    const res = await fetch(url);
    if (!res.ok) {
      throw new Error('Network response was not ok ' + res.statusText);
    }
    const data = await res.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}
fetchWithErrorHandling('https://jsonplaceholder.typicode.com/posts');

Example Application

Let’s see an example of a simple application that fetches posts from an API and displays them using React:

import React, { useEffect, useState } from 'react'; import fetch from 'isomorphic-unfetch';
function App() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    async function loadPosts() {
      const res = await fetch('https://jsonplaceholder.typicode.com/posts');
      const data = await res.json();
      setPosts(data);
    }

    loadPosts();
  }, []);

  return (
    

Posts

    {posts.map(post => (
  • {post.title}

    {post.body}

  • ))}
); } export default App;

By using isomorphic-unfetch, you can create simple yet powerful applications that work seamlessly on both the client and server. We hope you found this guide useful and that it helps you get started with isomorphic-unfetch in your next project.

Hash: 48f64df63dc514f935bf19e05e53650efef8b65494ae090033154eb03abb7190

Leave a Reply

Your email address will not be published. Required fields are marked *