The tRPC setData hook is limited in its ability to access all data necessary for optimistic UI updates

As I integrate mutations using tRPC and React Query to optimistically update my UI upon adding a new item, I've encountered an issue.

The problem lies in the query I'm updating, which requires specific properties like auto-generated IDs or database-related relationships like tags. Is there a way to maintain type safety while utilizing the data passed into the onMutate callback without creating temporary data just to meet type constraints? This is how my onMutate function currently looks:

onMutate: (data) => {
      const previousJobs = utils.jobs.getAll.getData();
      if (previousJobs) {
        utils.jobs.getAll.setData((() => undefined)(),
        [...previousJobs, { ...data, status: JobStatus.OPEN, priority: JobPriority.NO_PRIORITY, id: "temp", created_at: new Date(), updated_at: new Date(), team_id: "temp", user_id: "temp" }]
        ); 
      }
    },

This is the error message I'm encountering:

 Type '{ status: "OPEN"; priority: "NO_PRIORITY"; id: string; created_at: Date; updated_at: Date; team_id: string; user_id: string; salary: number; title: string; office_type: string; description: string; due_date: Date; }' is missing the following properties from type '{ user: User & { view: { state: ViewState; }[]; }; _count: { tags: number; candidates: number; }; tags: { id: string; value: string; color: string; }[]; }'

Answer №1

An issue with optimistic updates is the need to anticipate and simulate server-side logic on the client side.

For a more in-depth explanation, check out: https://example.com/blog/optimistic-updates-explained

If your UI can function properly without certain fields, consider making them optional in your type definition. However, for mandatory fields like an id, you may need to generate placeholder values in the onMutate callback.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Configuration of injected services in IONIC 2

I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers. Previously, I asked a colleague who mentioned that IONIC 2 op ...

Learn how to deactivate the pause button with just one click and re-enable it once the popup appears using Angular2 and Typescript

Can anyone assist with solving an issue I am facing with a timer and a pause button? I need the pause button to be disabled once clicked, until a popup appears, then it should become enabled again. My code snippet is provided below: HTML: <button md-i ...

Encountered a build error during the execution of npm run build

An error occurred while the app was fetching data from a local Javascript file via an API. Below is the error message along with the code snippet: $ npm run build [email protected] build next build && next export Browserslist: caniuse-lite ...

The continuous re-rendering is being triggered by the Async/Await Function

I am facing an issue with fetching data from the backend using axios. The function is returning a Promise and each time I call it, my component keeps rendering continuously. Below is the code snippet: import { useState } from "react"; import Ax ...

Creating a custom autocomplete search using Angular's pipes and input

Trying to implement an autocomplete input feature for any field value, I decided to create a custom pipe for this purpose. One challenge I'm facing is how to connect the component displaying my JSON data with the component housing the autocomplete in ...

Sending properties in NextJS from the server side (Application routing)

In order to share data for each request, I have created an object with this data in the rootLayout. export interface IProps { children: React.ReactNode; data: any; } export default function RootLayout(props: IProps) { const {children} = props; ...

Does npm run use a separate version of TSC?

I am encountering an issue with my VS Code and Node.js project that uses Typescript. Within my package.json file's script block, there is an entry: "build-ts": "tsc" When I run simply tsc on the integrated terminal command line, the compilation proc ...

Compiling TypeScript files from multiple source directories

Having 3 NodeJs applications with the latest versions of Typescript code, each containing an "src" folder with TypeScript code files and a "dist" folder with JavaScript files compiled by Typescript. I am now looking to create a "common" folder outside of ...

Removing empty options from a select dropdown in Angular 9

In the process of working with Angular 9, I am currently in the process of constructing a dropdown menu that contains various options. However, I have encountered an issue where there is a blank option displayed when the page initially loads. How can I eli ...

Is there a way to transfer data to a different component in React without relying on a hierarchical parent-child relationship?

I am struggling to pass the data from the "SearchingData" Component to the "Search" Component. The SearchingData component is a child of the Search component. I need to transfer the data from the variable named "datacame" to the Search Component. Can som ...

Transmitting confidential information to the Next.js Link module

One aspect I'm curious about is the Link component from 'next-Link'. If I need to pass sensitive data, such as a category_id, how can I securely transmit it for use in the getServerSideProps() function without relying on query strings? ...

Leveraging BigCommerce as a Headless solution paired with Nextjs on the front end, and Nestjs on the backend

As a newcomer to the world of BC, I find the documentation a bit confusing. I am interested in utilizing BC APIs with Nextjs and Nestjs. The goal is to develop a traditional web application where Nestjs on the server communicates directly with BC APIs, w ...

Refreshing a page in Next.js causes query parameters to disappear

I am facing an issue with routing between two components and passing data from the first to the second without sending the parameter in the URL. The problem arises when I refresh the page and the query params are lost. <p className={styles.jobname}& ...

What are the differences between Modules and Typings in Typescript?

I have been searching far and wide for information on the variances between modules and typings in TypeScript, but I'm still struggling to grasp the concept. As a newcomer to TypeScript, could someone please provide a concise explanation of these diff ...

Exploring the use of MockBackend to test a function that subsequently invokes the .map method

I've been working on writing unit tests for my service that deals with making Http requests. The service I have returns a Http.get() request followed by a .map() function. However, I'm facing issues with getting my mocked backend to respond in a ...

What is the best way to instantiate objects, arrays, and object-arrays in an Angular service class?

How can I nest an object within another object and then include it in an array of objects inside an Angular service class? I need to enable two-way binding in my form, so I must pass a variable from the service class to the HTML template. trainer.service. ...

React component stuck in endless loop due to Intersection Observer

My goal is to track the visibility of 3 elements and update state each time one of them becomes visible. Despite trying various methods like other libraries, useMemo, useCallback, refs, etc., I still face challenges with my latest code: Endless loop scenar ...

Show the values in the second dropdown menu according to the selection made in the first dropdown menu using Angular 8

My goal is to retrieve data and populate two dropdowns based on user selection. However, the code I've written isn't giving me the desired output and instead, errors are occurring. Being new to Angular, I would appreciate a review of my code. Her ...

Button to expand or collapse all sections in Ant Design Collapse component

Is there a way to create a button that can expand or collapse all tabs in an ant.design Collapse component? I attempted to modify defaultActiveKey but it seems like this can only be done during page rendering. If possible, could someone share a code snip ...

Obtain the user's ID in string format from the clerk

I'm trying to retrieve the clerk ID to cross-reference with the backend. The issue is that the clerk is using a hook which isn't compatible with this function type. export const getServerSideProps = async ({ req }) => { const { isLoaded, is ...