T
TanStack15mo ago
flat-fuchsia

How to organize react query project

I have question about organizing react query, currently I have folder services with folders like users, posts, and there is file for server data fetching functions called api.ts, and another file for queries and mutations (queriesAndMutations.ts) would it be better solution to rename api.ts for example for posts, to postService, make it file that exports postService = new class postService, and there store all api calls as methods
2 Replies
flat-fuchsia
flat-fuchsiaOP15mo ago
something like this
// services/posts/postService.ts
class PostService {
async fetchPosts() {
// Fetch posts from the server
}

async createPost(postData: PostData) {
// Create a new post on the server
}

async updatePost(postId: string, updatedData: PostData) {
// Update a post on the server
}

async deletePost(postId: string) {
// Delete a post from the server
}
}

const postService = new PostService();
export default postService;
// services/posts/postService.ts
class PostService {
async fetchPosts() {
// Fetch posts from the server
}

async createPost(postData: PostData) {
// Create a new post on the server
}

async updatePost(postId: string, updatedData: PostData) {
// Update a post on the server
}

async deletePost(postId: string) {
// Delete a post from the server
}
}

const postService = new PostService();
export default postService;
// services/posts/queriesAndMutations.ts
import { useQuery, useMutation, useQueryClient } from 'react-query';
import postService from './postService';

export const usePosts = () => {
return useQuery('posts', postService.fetchPosts);
};

export const useCreatePost = () => {
const queryClient = useQueryClient();
return useMutation(postService.createPost, {
onSuccess: () => {
queryClient.invalidateQueries('posts');
},
});
};

// Similarly, you can add useUpdatePost and useDeletePost hooks
// services/posts/queriesAndMutations.ts
import { useQuery, useMutation, useQueryClient } from 'react-query';
import postService from './postService';

export const usePosts = () => {
return useQuery('posts', postService.fetchPosts);
};

export const useCreatePost = () => {
const queryClient = useQueryClient();
return useMutation(postService.createPost, {
onSuccess: () => {
queryClient.invalidateQueries('posts');
},
});
};

// Similarly, you can add useUpdatePost and useDeletePost hooks
flat-fuchsia
flat-fuchsiaOP15mo ago
or maybe keep api.ts so the project structure would be
services/
posts/
api.ts
postService.ts
queriesAndMutations.ts
types.ts
services/
posts/
api.ts
postService.ts
queriesAndMutations.ts
types.ts
No description

Did you find this page helpful?