diff --git a/client/src/components/MessageWrapper.tsx b/client/src/components/MessageWrapper.tsx
index ec29fb1..2a65d09 100644
--- a/client/src/components/MessageWrapper.tsx
+++ b/client/src/components/MessageWrapper.tsx
@@ -1,20 +1,12 @@
-import { useQuery } from "@tanstack/react-query";
import Message from "./Message";
-import { getMessages } from "@controllers/MessageController";
+import { useMessages } from "@controllers/MessageController";
const MessageWrapper = () => {
- const messages = useQuery(["messages"], getMessages, {
- onSuccess: (data) => {
- return data;
- },
- onError: (error) => {
- console.error(error);
- },
- });
+ const {messages, isLoading} = useMessages();
return (
- {messages.isLoading ? '' : messages.data?.map((message: any) => (
+ {isLoading ? '' : messages?.map((message: any) => (
))}
diff --git a/client/src/controllers/MessageController.ts b/client/src/controllers/MessageController.ts
index e4f2bac..3133781 100644
--- a/client/src/controllers/MessageController.ts
+++ b/client/src/controllers/MessageController.ts
@@ -1,3 +1,4 @@
+import { useState } from 'react';
import { Cookies } from 'react-cookie';
const getMessages = async () => {
@@ -12,6 +13,31 @@ const getMessages = async () => {
return data;
};
+const useMessages = () => {
+ const [messages, setMessages] = useState([]);
+ const [isLoading, setIsLoading] = useState(true);
+ const [isError, setIsError] = useState(false);
+ const [error, setError] = useState(null);
+
+ const fetchMessages = () => {
+ getMessages()
+ .then((messagesData) => {
+ setMessages(messagesData);
+ setIsLoading(false);
+ })
+ .catch((errorMsg) => {
+ setIsError(true);
+ setError(errorMsg);
+ });
+ };
+
+ if (isLoading) {
+ fetchMessages();
+ }
+
+ return { messages, isLoading, isError, error };
+};
+
const newMessage = async (data: FormData) => {
const token = new Cookies().get('token');
const response = await fetch('/api/posts/new', {
@@ -49,4 +75,4 @@ const editMessage = async (id: string, data: FormData) => {
return response.json();
};
-export { getMessages, newMessage, deleteMessage, editMessage };
+export { getMessages, newMessage, deleteMessage, editMessage, useMessages };