RTK update mutation: updating data efficiently without the need to refresh the page

I am facing an issue with my mui rating component in a post-rating scenario. Although the rating updates successfully in the data, the page does not refresh after a click event, and hence, the rating remains enabled. To address this, I have implemented a disable boolean that checks if the rating is non-zero upon loading and disables it accordingly.

Below is the implementation of the post component with the rating feature:

import { Button, Rating } from "@mui/material";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import {
  useGetPostByIdQuery,
  useUpdatePostByIdMutation,
} from "../../features/api/apiSlice";

type Post = {
  id: number;
  title: string;
  body: string;
  userId: number;
  date: string;
  rating: number;
};

export function SinglePost() {
  const { postId } = useParams();
  const [value, setValue] = useState<number | null>();

  const {
    data: post,
    isLoading,
    isSuccess,
    isError,
    refetch,
  } = useGetPostByIdQuery(Number(postId));

  const [updatePost] = useUpdatePostByIdMutation();

  let title;
  let body;
  let rating;
  if (isSuccess) {
    title = (
      <h1 style={{ color: "white", textAlign: "center" }}>{post.title}</h1>
    );
    body = <p style={{ color: "white", textAlign: "center" }}>{post.body}</p>;
    rating = (
      <Rating
        key={Math.random()}
        name="size-large"
        size="large"
        value={post.rating}
        onChange={(event, newValue) => {
          updatePost({
            id: Number(postId),
            title: post.title,
            body: post.body,
            userId: post.userId,
            date: post.date,
            rating: Number(newValue),
          });
        }}
        disabled={post.rating !== 0 ? true : false}
      />
    );
  } else if (isError) {
    title = <h1 style={{ color: "white" }}>Title Error!</h1>;
    body = <p>Body Error!</p>;
  }

  return (
    <div
      style={{
        height: "500px",
        backgroundColor: "rgb(10, 25, 41)",
        width: "500px",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        flexDirection: "column",
      }}
    >
      {title}
      <br />
      {body}
      <br />
      {rating}
    </div>
  );
}

Additionally, here is the query mutation defined in my api slice:

import {
  createEntityAdapter,
  createSelector,
  EntityState,
} from "@reduxjs/toolkit";
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

type Post = {
  id: number;
  title: string;
  body: string;
  userId: number;
  date: string;
  rating: number;
};

// Rest of the API slice code...

I am unsure why the page does not automatically refetch after changing the rating. Any insights on resolving this issue would be greatly appreciated.

Answer №1

A problem was identified with your getPostsById function not refreshing data following the updatePost action that invalidated the LIST due to lack of tags in getPostsById.

To ensure the subroute for each post refreshes after an update, you must include the same tag on the endpoint as you invalidate on the update post endpoint.

To resolve this issue, modify the endpoints getPostById and updatePostById as follows:

{
   getPostById: builder.query<Post, number>({
      query: (id) => `/posts/${id}`,
      provideTags: (_, _, args) => [{ type: "Posts", id: args.id }],
   }),
   updatePostById: builder.mutation<Post, Partial<Post>>({
      query: (post: Post) => {
        const { id, ...body } = post;
        return {
          url: `posts/${id}`,
          method: "PUT",
          body,
        };
      },
      invalidatesTags: (_, _, post) => [{ type: "Posts", id: post.id }],
   }),
}

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

Top choice for React with TypeScript CodeMirror integration

Seeking recommendations for a package that seamlessly integrates with typescript in an existing react application. Specifically, looking to implement codeMirror functionality. Any suggestions? ...

Troubleshooting: NextJS Typescript getInitialProps returning null value

I am currently working with NextJS 'latest' and TypeScript to extract the token from the URL, but I am encountering an issue where it returns undefined. To achieve this, I am utilizing the getInitialProps method. The URL in question looks like th ...

"When attempting to render a Node inside the render() method in React, the error message 'Objects are not valid as a React child' is

On my webpage, I have managed to display the following: export class OverworldComponent extends React.Component<OverworldComponentProps, {}> { render() { return <b>Hello, world!</b> } } However, instead of showing Hello, ...

Determining the instance type of a TypeScript singleton class

I have a unique singleton implementation: class UniqueSingleton { private static instance: UniqueSingleton; private constructor() { // Only allows instantiation within the class } public static getInstance(): UniqueSingleton { if (!Unique ...

Choosing the Perfect Title for Your MUI X Data Grid

I'm currently experimenting with the MUI X Data Grid React Component, which is licensed under MIT. Is there a way to include a title above the column headers but below the border of the Data Grid? I'd prefer simple centered text or even custom c ...

Encountered an issue while attempting to load the TSLint library for the document within Visual Studio Code

After setting up the latest versions of Visual Studio Code, Node.js, and Typescript on my Windows 10 system, I encountered an issue when trying to utilize TSLint in the terminal. A message appeared stating: Failed to load the TSLint library for the documen ...

Tips on efficiently adding and removing elements in an array at specific positions, all the while adjusting the positions accordingly

My challenge involves an array of objects each containing a position property, as well as other properties. It looks something like this: [{position: 1, ...otherProperties}, ...otherObjects] On the frontend, these objects are displayed and sorted based on ...

What is the best way to write a function in typescript that verifies whether the argument extends a type argument and then returns the argument?

I need to create a function that checks if the argument's type extends a specific type variable and then returns the argument. Something like this: declare function checkType<T, X extends T>(argument: X): X However, TypeScript gives an error wh ...

Struggling to make Typescript recognize the css prop (emotion) when styling Material-UI components

I'm on a mission to set up a Typescript project with Material-UI v4.11.4 and implement emotion for styling in anticipation of the MUI v5 release. The aim is to integrate emotion into the project so developers can transition to using the new styling in ...

Discover the use of dot notation for accessing nested properties

In the deps array below, I aim to enforce type safety. Only strings allowed should be in dot notation of ${moduleX}.${moduleX service} // Modules each have a factory function that can return a services object (async) createModules({ data: { factory: ...

Efficient access to variable-enumerated objects in TypeScript

Let's say I have the following basic interfaces in my project: interface X {}; interface Y {}; interface Data { x: X[]; y: Y[]; } And also this function: function fetchData<S extends keyof Data>(type: S): Data[S] { return data[type]; } ...

The specified function 'isFakeTouchstartFromScreenReader' could not be located within the '@angular/cdk/a11y' library

I encountered the following errors unexpectedly while working on my Angular 11 project: Error: ./node_modules/@angular/material/fesm2015/core.js 1091:45-77 "export 'isFakeTouchstartFromScreenReader' was not found in '@angular/cdk/a11y&a ...

What is the process for using infer to determine the return type of a void function?

I am trying to gain a better understanding of how to utilize the infer keyword in TypeScript. Is this an appropriate example demonstrating the correct usage of infer? I simply want to infer the return type of the function below: const [name, setName] = u ...

Concerns with combining key value pairs in Typescript Enums

Could you help me figure out how to properly implement an enum in my drop-down so that I can only display one value at a time? Currently, I am seeing both the key and the value in the list. This is my enum: export enum VMRole { "Kubemaster" = 0, "Kub ...

Angular 17 Pokedex Encyclopedia

Recently, I tackled a challenge during my Boot Camp where I had to create a Pokedex using pokeapi. After successfully completing the challenge, I decided to refine some aspects of it. However, I encountered an unusual issue when delving into the details of ...

What is the method for extracting children from a singular object in json-server rather than an array?

I am currently utilizing json-server as a mock-backend to fetch child data from a single object. The main table is called sentinel and the secondary table is named sensor It can be observed that sensors is an array, while sentinel is an object. I have ...

Toggle the Material UI checkbox based on the value received from an object input

I am facing an issue with an unchecked checkbox in my project. I am attempting to update its value based on data retrieved from an object. The object contains boolean values from an SQL query, either 'T' for true or 'F' for false. My in ...

Exploring the capabilities of extending angular components through multiple inheritance

Two base classes are defined as follows: export class EmployeeSearch(){ constructor( public employeeService: EmployeeService, public mobileFormatPipe: MobileFormatPipe ) searchEmployeeById(); searchEmployeeByName(); } ...

Creating instance methods in a TypeScript object can be accomplished by defining the methods within the object's class definition. When the object is

As a seasoned Java developer, I've recently been dabbling in TypeScript. Let me introduce you to my user object: export class User { id: string; name: string; email?: string; unit: string; street: string; postalcode: string; ...

How can I utilize generic types in Typescript/React when crafting a component with prop types?

I am facing an issue with a component that has a generic definition as shown below: export type CheckboxItem = { label: string, code: string, }; export type CheckboxesProps = { items: CheckboxItem[], handleStateChange: (selected: (CheckboxItem[&ap ...