blob: 92cc80de9b6919c1ffdb7303f9a18d724f3f9867 [file] [log] [blame]
simon26e79f72022-10-05 22:16:08 -04001/*
2 * Copyright (C) 2022 Savoir-faire Linux Inc.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation; either version 3 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public
15 * License along with this program. If not, see
16 * <https://www.gnu.org/licenses/>.
17 */
simond47ef9e2022-09-28 22:24:28 -040018import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
idillon08f77172022-09-13 19:14:17 -040019
simon5da8ca62022-11-09 15:21:25 -050020import { useAuthContext } from '../contexts/AuthProvider';
simon5da8ca62022-11-09 15:21:25 -050021
22export const useConversationQuery = (conversationId: string) => {
simon94fe53e2022-11-10 12:51:58 -050023 const { axiosInstance } = useAuthContext();
24 return useQuery(
25 ['conversation', conversationId],
26 async () => {
27 const { data } = await axiosInstance.get(`/conversations/${conversationId}`);
28 return data;
29 },
30 {
31 enabled: !!conversationId,
32 }
33 );
simond47ef9e2022-09-28 22:24:28 -040034};
idillon08f77172022-09-13 19:14:17 -040035
simon5da8ca62022-11-09 15:21:25 -050036export const useMessagesQuery = (conversationId: string) => {
simon94fe53e2022-11-10 12:51:58 -050037 const { axiosInstance } = useAuthContext();
38 return useQuery(
39 ['messages', conversationId],
40 async () => {
41 const { data } = await axiosInstance.get(`/conversations/${conversationId}/messages`);
42 return data;
43 },
44 {
45 enabled: !!conversationId,
46 }
47 );
simond47ef9e2022-09-28 22:24:28 -040048};
idillon08f77172022-09-13 19:14:17 -040049
simon5da8ca62022-11-09 15:21:25 -050050export const useSendMessageMutation = (conversationId: string) => {
simon94fe53e2022-11-10 12:51:58 -050051 const { axiosInstance } = useAuthContext();
simond47ef9e2022-09-28 22:24:28 -040052 const queryClient = useQueryClient();
53 return useMutation(
simon94fe53e2022-11-10 12:51:58 -050054 (message: string) => axiosInstance.post(`/conversations/${conversationId}/messages`, { message }),
simond47ef9e2022-09-28 22:24:28 -040055 {
simon5da8ca62022-11-09 15:21:25 -050056 onSuccess: () => queryClient.invalidateQueries(['messages', conversationId]),
simond47ef9e2022-09-28 22:24:28 -040057 }
58 );
59};