Skip to content

Conversation

danybeltran
Copy link
Member

@danybeltran danybeltran commented Dec 11, 2024

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>
  )
}

Adds the 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
@danybeltran danybeltran merged commit 86d7d93 into master Dec 11, 2024
2 checks passed
@danybeltran danybeltran deleted the features/transform branch July 27, 2025 16:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant