Skip to content

Commit

Permalink
Components are now more clear
Browse files Browse the repository at this point in the history
Queries got separated in custom hooks
  • Loading branch information
Ekrem05 committed Jul 1, 2024
1 parent 7305432 commit fc599d3
Show file tree
Hide file tree
Showing 8 changed files with 211 additions and 114 deletions.
59 changes: 5 additions & 54 deletions src/client/CookingAppFE/components/bot/ChatInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,67 +2,18 @@ import { View, Image, TextInput, TouchableOpacity } from "react-native";
import tw from "twrnc";
import { uiActions } from "../../redux/uiSlice";
import { useSelector, useDispatch } from "react-redux";
import { useMutation } from "@tanstack/react-query";
import { newChat, continueChat } from "../../http/chat";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { userActions } from "../../redux/userSlice";
import useChatMutation from "../../hooks/useNewChat";
import useContinueChatMutation from "../../hooks/useKeepChatting";
export default function ChatInput() {
const input = useSelector((state) => state.ui.input);
const isDarkTheme = useSelector((state) => state.ui.isDarkTheme);
const selectedChat = useSelector((state) => state.user.selectedChat);
const dispatch = useDispatch();
const {
mutate: initialMessage,
isPending,
isError,
error,
} = useMutation({
mutationFn: newChat,
onMutate: () => {
dispatch(uiActions.setIsThinking(true));
dispatch(uiActions.setInput(""));
},
onSuccess: (response) => {
dispatch(
userActions.selectChat({
id: response.data.chatId,
title: response.data.title,
content: [
...selectedChat.content,
{ role: "bot", content: response.data.response },
],
})
);
dispatch(uiActions.setInput(""));
dispatch(uiActions.setIsThinking(false));
},
});
const {
mutate: keepChatting,
isPending: isChatting,
isError: isChatError,
error: chatError,
} = useMutation({
mutationKey: "continue",
mutationFn: continueChat,
onMutate: () => {
dispatch(uiActions.setIsThinking(true));
dispatch(uiActions.setInput(""));
},
onSuccess: (response) => {
dispatch(
userActions.selectChat({
...selectedChat,
content: [
...selectedChat.content,
{ role: "bot", content: response.data.response },
],
})
);
dispatch(uiActions.setIsThinking(false));
},
onError: (error) => {},
});
const { initialMessage, isPending, isError, error } = useChatMutation();
const { keepChatting, isChatting, isChatError, chatError } =
useContinueChatMutation();

async function sendMessage() {
const token = await AsyncStorage.getItem("token");
Expand Down
1 change: 0 additions & 1 deletion src/client/CookingAppFE/components/bot/Home.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ const Home = () => {
const isDarkTheme = useSelector((state) => state.ui.isDarkTheme);
const isThinking = useSelector((state) => state.ui.isThinking);
const chat = useSelector((state) => state.user.selectedChat);

useEffect(() => {
const checkToken = async () => {
const token = await AsyncStorage.getItem("token");
Expand Down
67 changes: 9 additions & 58 deletions src/client/CookingAppFE/components/navigation/Sidebar.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,63 +14,20 @@ import AsyncStorage from "@react-native-async-storage/async-storage";
import { useDispatch, useSelector } from "react-redux";
import { jwtDecode } from "jwt-decode";
import Ionicons from "react-native-vector-icons/Ionicons";
import { useMutation, useQuery } from "@tanstack/react-query";
import { getChat, getUserChats } from "../../http/chat";
import useSelectChat from "../../hooks/useSelectChat";
import { userActions } from "../../redux/userSlice";
import useChatHistory from "../../hooks/useChatHistory";
const Sidebar = ({ open, setOpen }) => {
const isDarkTheme = useSelector((state) => state.ui.isDarkTheme);
const chat = useSelector((state) => state.user.selectedChat);
const chatHistory = useSelector((state) => state.user.chatHistory);
const selectChat = useSelectChat();
const { refetchChatHistory } = useChatHistory();
const dispatch = useDispatch();
const {
data: chatHistory,
isPending,
isError,
error,
refetch,
} = useQuery({
queryKey: ["getHistory"],
queryFn: async () => {
const token = await AsyncStorage.getItem("token");
const decodedToken = jwtDecode(token);
return (
decodedToken && getUserChats({ token: token, userId: decodedToken.sub })
);
},
});
const { mutate } = useMutation({
mutationFn: getChat,
onSuccess: (response) => {
const { requests, responses } = response.data.chat;
const minLength = Math.min(requests.length, responses.length);
let combinedArray = [];
for (let i = 0; i < minLength; i++) {
combinedArray.push({ content: requests[i], role: "user" });
combinedArray.push({ content: responses[i], role: "bot" });
}

for (let i = minLength; i < requests.length; i++) {
combinedArray.push({ content: requests[i], role: "user" });
}

for (let i = minLength; i < responses.length; i++) {
combinedArray.push({ content: responses[i], role: "bot" });
}
dispatch(
userActions.selectChat({
id: response.data.id,
title: response.data.title,
content: combinedArray,
})
);
setOpen(false);
},
});
const navigation = useNavigation();
const [animation] = useState(new Animated.Value(-300));
useEffect(() => {
refetch();
refetchChatHistory();
}, [chat]);
console.log(chatHistory);
useEffect(() => {
if (open) {
Animated.timing(animation, {
Expand All @@ -88,19 +45,13 @@ const Sidebar = ({ open, setOpen }) => {
}, [open, animation]);

const handleChatPress = async (chat) => {
const token = await AsyncStorage.getItem("token");
if (token) {
mutate({ token, chatId: chat.id });
} else {
navigation.navigate("LandingPage");
}
selectChat(chat);
setOpen(false);
};

const startNewChat = () => {
navigation.navigate("Home");
dispatch(userActions.clearChat());
setOpen(false);
};

const getSectionTitle = (date) => {
const today = new Date();
const chatDate = new Date(date);
Expand Down
51 changes: 51 additions & 0 deletions src/client/CookingAppFE/hooks/useChatHistory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { useEffect } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useSelector, useDispatch } from "react-redux";
import { jwtDecode } from "jwt-decode";
import { useQuery } from "@tanstack/react-query";
import { getUserChats } from "../http/chat";
import { userActions } from "../redux/userSlice";

const useChatHistory = () => {
const dispatch = useDispatch();
const chatHistory = useSelector((state) => state.user.chatHistory);

const {
data: chatHistoryData,
isPending,
isError,
error,
refetch,
} = useQuery({
queryKey: ["getHistory"],
queryFn: async () => {
const token = await AsyncStorage.getItem("token");
const decodedToken = jwtDecode(token);
const userChats = await getUserChats({
token: token,
userId: decodedToken.sub,
});
return userChats;
},
});

useEffect(() => {
refetch();
}, []);

useEffect(() => {
if (chatHistoryData) {
dispatch(userActions.setChatHistory(chatHistoryData));
}
}, [chatHistoryData]);

return {
chatHistory,
isPending,
isError,
error,
refetchChatHistory: refetch,
};
};

export default useChatHistory;
46 changes: 46 additions & 0 deletions src/client/CookingAppFE/hooks/useKeepChatting.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { useMutation } from "@tanstack/react-query";
import { useDispatch, useSelector } from "react-redux";
import { userActions } from "../redux/userSlice";
import { continueChat } from "../http/chat";
import { uiActions } from "../redux/uiSlice";
const useContinueChatMutation = () => {
const dispatch = useDispatch();
const selectedChat = useSelector((state) => state.user.selectedChat);

const {
mutate: keepChatting,
isPending: isChatting,
isError: isChatError,
error: chatError,
} = useMutation({
mutationKey: "continue",
mutationFn: continueChat,
onMutate: () => {
dispatch(uiActions.setIsThinking(true));
dispatch(uiActions.setInput(""));
},
onSuccess: (response) => {
const newChatMessage = {
role: "bot",
content: response.data.response,
};
dispatch(
userActions.selectChat({
...selectedChat,
content: [...(selectedChat.content || []), newChatMessage],
})
);
dispatch(uiActions.setIsThinking(false));
},
onError: (error) => {},
});

return {
keepChatting,
isChatting,
isChatError,
chatError,
};
};

export default useContinueChatMutation;
46 changes: 46 additions & 0 deletions src/client/CookingAppFE/hooks/useNewChat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { useMutation } from "@tanstack/react-query";
import { useDispatch, useSelector } from "react-redux";
import { newChat } from "../http/chat";
import { uiActions } from "../redux/uiSlice";
import { userActions } from "../redux/userSlice";
const useChatMutation = () => {
const dispatch = useDispatch();
const selectedChat = useSelector((state) => state.user.selectedChat);

const {
mutate: initialMessage,
isPending,
isError,
error,
} = useMutation({
mutationFn: newChat,
onMutate: () => {
dispatch(uiActions.setIsThinking(true));
dispatch(uiActions.setInput(""));
},
onSuccess: (response) => {
const newChatMessage = {
role: "bot",
content: response.data.response,
};
dispatch(
userActions.selectChat({
id: response.data.chatId,
title: response.data.title,
content: [...(selectedChat.content || []), newChatMessage],
})
);
dispatch(uiActions.setInput(""));
dispatch(uiActions.setIsThinking(false));
},
});

return {
initialMessage,
isPending,
isError,
error,
};
};

export default useChatMutation;
53 changes: 53 additions & 0 deletions src/client/CookingAppFE/hooks/useSelectChat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useNavigation } from "@react-navigation/native";
import { useDispatch } from "react-redux";
import { useMutation } from "@tanstack/react-query";
import { getChat } from "../http/chat";
import { userActions } from "../redux/userSlice";

const useSelectChat = () => {
const dispatch = useDispatch();
const navigation = useNavigation();

const { mutate } = useMutation({
mutationFn: getChat,
onSuccess: (response) => {
const { requests, responses } = response.data.chat;
const minLength = Math.min(requests.length, responses.length);
let combinedArray = [];
for (let i = 0; i < minLength; i++) {
combinedArray.push({ content: requests[i], role: "user" });
combinedArray.push({ content: responses[i], role: "bot" });
}

for (let i = minLength; i < requests.length; i++) {
combinedArray.push({ content: requests[i], role: "user" });
}

for (let i = minLength; i < responses.length; i++) {
combinedArray.push({ content: responses[i], role: "bot" });
}
dispatch(
userActions.selectChat({
id: response.data.id,
title: response.data.title,
content: combinedArray,
})
);
navigation.navigate("Home");
},
});

const selectChat = async (chat) => {
const token = await AsyncStorage.getItem("token");
if (token) {
mutate({ token, chatId: chat.id });
} else {
navigation.navigate("LandingPage");
}
};

return selectChat;
};

export default useSelectChat;
2 changes: 1 addition & 1 deletion src/client/CookingAppFE/redux/userSlice.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const userSlice = createSlice({
state.selectedChat = null;
},
setChatHistory(state, action) {
state.selectedChat = action.payload;
state.chatHistory = action.payload;
},
},
});
Expand Down

0 comments on commit fc599d3

Please sign in to comment.