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

How to pass data/props to a dynamic page in NextJS?

Currently, I am facing a challenge in my NextJS project where I am struggling to pass data into dynamically generated pages. In this application, I fetch data from an Amazon S3 bucket and then map it. The fetching process works flawlessly, generating a se ...

The specified instant cannot be located in 'moment' while attempting to import {Moment} from 'moment' module

Struggling in a reactJS project with typescript to bring in moment alongside the type Moment Attempted using import moment, { Moment } from 'moment' This approach triggers ESLint warnings: ESLint: Moment not found in 'moment'(import/n ...

Type Vue does not contain the specified property

I am encountering an issue where I am using ref to retrieve a value, but I keep receiving the error message "Property 'value' does not exist on type 'Vue'". Below is the code snippet causing the problem: confirmPasswordRules: [ ...

Having trouble updating the value in the toolbar?

Here is an example that I added below: When I click the add button, the value of the "newarray" variable is updated but not reflected. I am unsure how to resolve this issue. This function is used to add new objects: export class AppComponent { ne ...

AngularJS - Unusual outcomes observed while utilizing $watch on a variable from an external AngularJS service

Within the constructor of my controllers, I execute the following function: constructor(private $scope, private $log : ng.ILogService, private lobbyStorage, private socketService) { this.init(); } private init(){ this.lobbyData = []; this.initial ...

The custom validation in nestjs is throwing an error due to an undefined entity manager

I've been working on developing a custom validation for ensuring unique values in all tables, but I encountered this error: ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'getRepository') TypeError: Cannot read proper ...

Display your StencilJs component in a separate browser window

Looking for a solution to render a chat widget created with stenciljs in a new window using window.open. When the widget icon is clicked, a new window should open displaying the current state while navigating on the website, retaining the styles and functi ...

Protected members in Angular 2 component templates using TypeScript

Reflecting on ways to incorporate members in a component that can be accessed from the template but not from a parent component sparked my curiosity. In exploring TypeScript visibility in Angular 2, I encountered discussions about "public" and "private" d ...

What is the purpose of exporting both a class and a namespace under the same name?

While exploring some code, I came across a situation where a class and a namespace with identical names were exported from a module. It seems like the person who wrote this code knew what they were doing, but it raised some questions for me. Could you shed ...

An unexpected issue occurred while attempting to create a new Angular app using the command ng

Currently in the process of deploying my angular application and utilizing Infragistics. Following their Documentation, I used npm install Infragistics for installation. However, when I run ng new --collection="@igniteui/angular-schematics" I e ...

In Angular 16, allow only the row that corresponds to the clicked EDIT button to remain enabled, while disabling

Exploring Angular and seeking guidance on a specific task. I currently have a table structured like this: https://i.stack.imgur.com/0u5GX.png This code is used to populate the table: <tbody> <tr *ngFor="let cus of customers;" [ngClass ...

When compiling to ES5, TypeScript fails to remove imports

I am working on a TypeScript file that utilizes the moment library, and I need to import moment for it to compile properly. However, after compilation, the import line is still present in the compiled file, which is causing issues on my web page. Here is ...

Issues with TypeScript: Difficulty locating names in HTML templates

I recently upgraded my Angular 7 code to Angular 9 by following the steps outlined in the Angular Upgrade guide. However, upon completion of the migration process, I started encountering numerous "Cannot find name" errors within the HTML templates of my co ...

Unlocking rotation on a single screen in a react native application can be achieved by altering

I attempted to use react-native-orientation within a webview in order to make it the only view that would rotate. import React, {useEffect} from 'react'; import { WebView } from 'react-native-webview'; import Orientation from "react-na ...

I'm currently facing an issue where the Ionic styles are not displaying correctly within my Next.js application

I'm currently experiencing a problem where Ionic styles are not being applied to certain pages in my Next.js app. Despite working on the home page, the Ionic styles do not seem to be taking effect on the profile page. Any guidance on troubleshooting t ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

How can I work with numerous "Set-Cookie" fields in NextJS-getServerSideProps?

When working with getServerSideProps, I found a way to set multiple cookies on the client device. This is the code snippet that I used: https://i.stack.imgur.com/Kbv70.png ...

Restricting the data type of a parameter in a TypeScript function based on another parameter's value

interface INavigation { children: string[]; initial: string; } function navigation({ children, initial }: INavigation) { return null } I'm currently working on a function similar to the one above. My goal is to find a way to restrict the initi ...

The Observable.subscribe method does not get triggered upon calling the BehaviorSubject.next

In my Navbar component, I am attempting to determine whether the user is logged in or not so that I can enable/disable certain Navbar items. I have implemented a BehaviorSubject to multicast the data. The AuthenticationService class contains the BehaviorSu ...

I am experiencing an issue with my service provider when it comes to displaying multiple navigator stacks

Currently, I am developing a provider to manage the user's state across different views. The primary function of this provider is to display either one stack navigator or another based on whether a certain variable is filled or empty. This setup allow ...