Skip to content

v3.7.4

Choose a tag to compare

@danybeltran danybeltran released this 11 Dec 22:11
· 24 commits to master since this release
86d7d93

v3.7.4

Transform API

  • Similar to middleware but it transforms data on the fly without making a new request (happens instantly)
  • transform first checks data is not undefined before running, which makes sure it only runs when data or fallback data exist, preventing (most) runtime errors that could arise when manipulatind data that could be undefined.

Example usage:

"use client"

import useFetch from "http-react"
import { useState } from "react"

import { type TodoType } from "@/types/todo"

export default function Home() {
  const [showUppercase, setShowUppercase] = useState(false)

  const { data, isLoading } = useFetch<TodoType>(
    "https://jsonplaceholder.typicode.com/todos/2",
    {
      // Supports TypeScript out of the box
      transform(data) {
        if (showUppercase) {
          const transformedTodo = {
            ...data,
            title: data?.title.toUpperCase(),
          }
          return transformedTodo
        }
        return data
      },
    }
  )

  if (isLoading) return <p>Loading...</p>

  return (
    <main>
      <button onClick={() => setShowUppercase(!showUppercase)}>
        Uppercase: {showUppercase ? "ON" : "OFF"}
      </button>

      <h2>Title: {data.title}</h2>
    </main>
  )
}