Skip to content

Instantly share code, notes, and snippets.

@iamparthaonline
Last active July 9, 2025 03:53
Show Gist options
  • Select an option

  • Save iamparthaonline/27b527fd53000e41d50bbe7559e2d717 to your computer and use it in GitHub Desktop.

Select an option

Save iamparthaonline/27b527fd53000e41d50bbe7559e2d717 to your computer and use it in GitHub Desktop.
// redux/api.js
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
tagTypes: ['Post'],
endpoints: (builder) => ({
getPosts: builder.query({
query: () => 'posts',
providesTags: (result) =>
result
? [
...result.map(({ id }) => ({ type: 'Post', id })),
{ type: 'Post', id: 'LIST' },
]
: [{ type: 'Post', id: 'LIST' }],
}),
getPost: builder.query({
query: (id) => `posts/${id}`,
providesTags: (result, error, id) => [{ type: 'Post', id }],
}),
addPost: builder.mutation({
query: (newPost) => ({
url: 'posts',
method: 'POST',
body: newPost,
}),
invalidatesTags: [{ type: 'Post', id: 'LIST' }],
}),
updatePost: builder.mutation({
query: ({ id, ...patch }) => ({
url: `posts/${id}`,
method: 'PATCH',
body: patch,
}),
invalidatesTags: (result, error, { id }) => [{ type: 'Post', id }],
}),
}),
})
export const {
useGetPostsQuery,
useGetPostQuery,
useLazyGetPostQuery,
useAddPostMutation,
useUpdatePostMutation,
} = api
// PostComponent.js
import React, { useState } from 'react'
import {
useGetPostsQuery,
useLazyGetPostQuery,
useAddPostMutation,
useUpdatePostMutation,
} from './redux/api'
function PostComponent() {
const { data: posts, isLoading, refetch } = useGetPostsQuery()
const [triggerGetPost, { data: postDetails }] = useLazyGetPostQuery()
const [addPost] = useAddPostMutation()
const [updatePost] = useUpdatePostMutation()
const [selectedPostId, setSelectedPostId] = useState(null)
const handleAdd = async () => {
await addPost({ title: 'New Post', content: 'Sample content' })
refetch()
}
const handleSelect = (id) => {
setSelectedPostId(id)
triggerGetPost(id)
}
const handleUpdate = async () => {
if (!selectedPostId) return
await updatePost({ id: selectedPostId, title: 'Updated Title' })
refetch()
}
if (isLoading) return <p>Loading posts...</p>
return (
<div>
<h2>Posts</h2>
<ul>
{posts?.map((post) => (
<li key={post.id}>
{post.title}
<button onClick={() => handleSelect(post.id)}>Details</button>
</li>
))}
</ul>
{postDetails && (
<div>
<h3>Selected Post</h3>
<p>{postDetails.title}</p>
</div>
)}
<button onClick={handleAdd}>Add Post</button>
<button onClick={handleUpdate}>Update Selected Post</button>
</div>
)
}
export default PostComponent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment