A trpc-ified useReducer hook. ⚑

Overview

trpc-reducer

  • A trpc-ified react useReducer hook that lets you perform state logic in reducers just like React's useReducer hook
  • When you dispatch an action, the new state updates the cache on the mutation's onSettled() function

Installation

npm install trpc-reducer trpc

Usage

first create your reducer hook:

// utils/trpc.ts
import { createTrpcReducer } from 'trpc-reducer'
import type { AppRouter } from './router'

export const trpc = createReactQueryHooks<AppRouter>()
export const trpcReducer = createTrpcReducer<AppRouter>(trpc)

then, create your reducer:

// utils/reducer.ts
import type { ReducerActions, ReducerOutput } from 'trpc-reducer'
import type { AppRouter } from './trpc'

export function myReducer(
  state: any,
  action: ReducerActions<AppRouter>,
): ReducerOutput<AppRouter> {
  switch (action.type[0]) {
    case 'example.user.create':
      return {
        users: [...state.users, action.payload],
      }

    case 'example.user.delete':
      return {
        users: state.users.filter((user: any) => user.id !== action.payload.id),
      }
    default:
      return state
  }
}

Use it:

// pages/_index.tsx
import { trpcReducer } from '../utils/trpc'
import { myReducer } from './reducer'

const Index = () => {
  const [input, setInput] = useState('')
  const { state, dispatch } = trpcReducer.useTrpcReducer(
    // your reducer
    myReducer,
    // fetch state
    ['example.users.get'],
    // your actions
    {
      arg_0: ['example.user.create'],
    },
  )

  return (
    <main>
      <form
        onSubmit={(e) => {
          e.preventDefault()
          dispatch({
            payload: {
              name: input,
              id: new Date().toTimeString().slice(0, 8),
            },
            type: ['example.user.create'],
          })
          setInput('')
        }}
      >
        <label htmlFor='name'>Name</label>
        <input
          type='text'
          name='name'
          id='name'
          value={input}
          onChange={(e) => setInput(e.target.value)}
        />
        <button disabled={state.isDispatching} type='submit'>
          {state.isLoading ? 'loading...' : 'Add Name'}
        </button>
      </form>

      <ul>
        {state.data
          && state.data.users.map((user, idx) => (
            <li key={idx}>
              {user.name}
            </li>
          ))}
      </ul>
    </main>
  )
}
You might also like...

A fullstack TikTok clone with Nextjs, Prisma, trpc

TikTok Clone A fullstack TikTok clone with Nextjs, Prisma, trpc Live demo Official website: https://toptop-clone.vercel.app/ Main technology used The

Dec 19, 2022

Kaol Stack - Prisma, Expo, Next, TRPC, Solito, Tailwind - A monorepo template for a truly universal app

Kaol Stack - Prisma, Expo, Next, TRPC, Solito, Tailwind - A monorepo template for a truly universal app

Kaol Stack πŸ”¦ About A monorepo with Prisma, Next.js, Expo, tRPC, Authentication and Solito setup and configured to work together. With this setup you

Dec 21, 2022

Next.js + tRPC + Blitz.js Auth + Prisma. Fullstack app example

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Oct 12, 2022

A super simple minimal tRPC for next-js

Typed Routes A way to have fully typed routes in next, without all the complexity of tRPC. This is more for super minimal use cases, where you don't n

Dec 28, 2022

tRPC + Next.js

next-trpc A drop-in version of tRPC + Next.js. If you haven't seen tRPC before, it's an excellent Next.js-native solution vs a traditional REST or Gra

Dec 21, 2022

Animated sprite hook for react-three-fiber

use-animated-sprite Animated sprite hook for react-three-fiber Dependencies npm install @react-three/drei @react-three/fiber react three Installation

Dec 4, 2022

Directus Hook Extension: Version Control Changelog

Directus Hook Extension: Version Control Changelog

A Directus hook extension to push user written change summaries (from a singleton collection text field) to a changelog in a VCS server

Nov 27, 2022

An enchanced useState hook which keeps track of the states history, allowing you to undo and redo states.

useTimeline An enchanced useState hook which keeps track of the states history, allowing you to undo and redo states. useTimeline is a simple hook bas

Apr 22, 2022

πŸͺ React hook for subscribing to user's color scheme preference.

πŸͺ React hook for subscribing to user's color scheme preference.

use-prefers-color-scheme React hook for subscribing to user's color scheme preference. πŸš€ Getting Started πŸ‡ Jump Start npm install @anatoliygatt/use-

Dec 19, 2022
Comments
  • Adapt number of useMutation() instances to the number of action arguments

    Adapt number of useMutation() instances to the number of action arguments

    Currently the useTrpcReducer hook takes in a arbitrary amount of actions

      actions: {
          arg_0: TMutationPath
          arg_1?: TMutationPath
          arg_2?: TMutationPath
          arg_3?: TMutationPath
          arg_4?: TMutationPath
        },
    

    The reason for this is because the useMutation() hook can't be called conditionally or in a function (rules of hooks) & hence it seems to me like i need to define the number of actions in advance in order to call the mutation instances like so

    const firstProcedureMutation = useMutation(actions.arg_0)
    const secondProcedureMutation = useMutation(actions.arg_1 ? actions.arg_1 : [''])
    const thirdProcedureMutation = useMutation(actions.arg_2 ? actions.arg_2 : [''])
    const fourthProcedureMutation = useMutation(actions.arg_3 ? actions.arg_3 : [''])
    const fifthProcedureMutation = useMutation(actions.arg_4 ? actions.arg_4 : [''])
    

    This is obsviously really ugly and was just a quick solutation at first, but after a week im still stuck at this solution because I can't figure out how to adapt the number of useMutation() instances to the number of action arguments

    This also leads to a dispatch function that looks like this

     function dispatch(action: TDispatch<TRouter>, opts?: TOpts) {
          const { type } = action
          if (type[0] === actions.arg_0[0]) {
            updateState({ mutation: firstProcedureMutation, action, opts })
          }
          if (actions.arg_1 && type[0] === actions.arg_1[0]) {
            updateState({ mutation: secondProcedureMutation, action, opts })
          }
          if (actions.arg_2 && type[0] === actions.arg_2[0]) {
            updateState({ mutation: thirdProcedureMutation, action, opts })
          }
          if (actions.arg_3 && type[0] === actions.arg_3[0]) {
            updateState({ mutation: fourthProcedureMutation, action, opts })
          }
          if (actions.arg_4 && type[0] === actions.arg_4[0]) {
            updateState({ mutation: fifthProcedureMutation, action, opts })
          }
        }
        return { state: procedureQuery, dispatch }
      }
    

    I think that the if statement is neccessary in order to supply the right action to the updateState function but again, I need some type of for-loop/mapping instead of these hardcoded mutations so that you can dynamically input any number of actions to useTrpcReducer and call updateState for every action argument.

    Do we have any ideas on how to go about this?

    opened by gabriel-frattini 0
Owner
gabriel-frattini
I study CS but spend most of my time onπŸ›'s
gabriel-frattini
Like useReducer, but runs in a worker.

useWorkerizedReducer useWorkerizedReducer is like useReducer, but the reducer runs in a worker. This makes it possible to place long-running computati

Surma 221 Dec 1, 2022
End-to-end typesafe APIs with tRPC.io in SvelteKit applications

✨ tRPC-SvelteKit End-to-end typesafe APIs with tRPC.io in SvelteKit applications. No code generation, run-time bloat, or build pipeline. ❀️ ???? See b

Ionut-Cristian Florescu 307 Dec 29, 2022
Prisma 2+ generator to emit fully implemented tRPC routers

Prisma tRPC Generator Automatically generate fully implemented tRPC routers from your Prisma Schema. This includes routers, app router and of course a

Omar Dulaimi 370 Jan 3, 2023
Prisma +2 generator to emit a tRPC shield from your Prisma schema

Prisma tRPC Shield Generator Automatically generate a tRPC Shield from your Prisma Schema. Updates every time npx prisma generate runs. Table of Conte

Omar Dulaimi 27 Dec 24, 2022
Proof of concept: support immutable trpc servers using lambdas to ensure client/server compatibility

auto-versioned-trpc-aws-lambda Proof of concept to support an automatically versioned AWS Lambda running tRPC to ensure a somewhat graceful and automa

Kenneth Skovhus 5 Aug 30, 2022
tRPC test & precursor to a billion dollar social cat network

CatMash What is this? Have you ever wanted to rank 11,000 cat pictures by cuteness? Of course you have. That's what we're doing here. This is an app b

Christopher Ehrlich 6 Dec 18, 2022
OpenAPI support for tRPC 🧩

trpc-openapi OpenAPI support for tRPC ?? Easy REST endpoints for your tRPC procedures. Perfect for incremental adoption. OpenAPI version 3.0.3. Usage

James Berry 841 Jan 9, 2023
Scaffold a full-stack SvelteKit application with tRPC and WindiCSS out of the box

create-sweet-app Interactive CLI to quickly set up an opinionated, full-stack, typesafe SvelteKit project. Inspired by the T3 Stack and create-t3-app

David HrabΔ› 10 Dec 16, 2022
NX monorepo showing the TMDB Watchlist mobile app with Expo, tRPC, Next, and Prisma

tmdb-watchlist-prisma This app uses TMDB to retrieve a list of Now Playing movies. You can add/remove movies to track which ones you've watched. There

Mat Warger 65 Dec 28, 2022
Qwik City adapter for trpc.io

tRPC ?? Qwik City End-to-end typesafe APIs made easy with tRPC.io in Qwik City applications. Build & consume fully typesafe APIs, without schemas or c

Giorgio Boa 29 Oct 11, 2022