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.