Skip to content

Commit

Permalink
refact chat.jsx
Browse files Browse the repository at this point in the history
  • Loading branch information
Lopkop committed Apr 2, 2024
1 parent e397ff6 commit 0566d13
Showing 1 changed file with 43 additions and 37 deletions.
80 changes: 43 additions & 37 deletions frontend/src/routes/Chat.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,43 +19,6 @@ const chatname = localStorage.getItem('chat')


export default function Chat() {
const [messages, setMessages] = useState([]);
useEffect(() => {
const fetchMessages = async () => {
try {
const response = await fetch(`http://localhost:8000/get-messages/${chatname}`, {
method: 'GET',
credentials: 'include'
})

const data = await response.json();
setMessages(data);
} catch (error) {
console.error('Error fetching messages:', error);
}
};
fetchMessages();
}, [chatname]);

function Message({ user, text, created_at }) {
return (
<div>
<div><strong>{user}</strong> ({created_at}):</div>
<div>{text}</div>
</div>
);
}

function MessageList({ messages }) {
return (
<div>
{messages.map((message, index) => (
<Message key={index} {...message} />
))}
</div>
);
}

const [user, setUser] = useState(null);
const [ws, setWs] = useState(null);
const messagesRef = useRef(null);
Expand All @@ -69,6 +32,9 @@ export default function Chat() {
const websocket = new WebSocket(`ws://localhost:8000/${chatname}/${response.name}`);
setWs(websocket);
}
else {
window.location.pathname = `/`;
}
}
fetchData();
}, []);
Expand All @@ -87,6 +53,36 @@ export default function Chat() {
}
}, [ws]);

const [messages, setMessages] = useState([]);
useEffect(() => {
const fetchMessages = async () => {
try {
const response = await fetch(`http://localhost:8000/get-messages/${chatname}`, {
method: 'GET',
credentials: 'include'
})

const data = await response.json();
setMessages(data);
} catch (error) {
console.error('Error fetching messages:', error);
}
};
fetchMessages();
}, [chatname]);

function Message({ user, text, created_at }) {
return (
<div>
<div><strong>{user}</strong> ({created_at}):</div>
<div>{text}</div>
</div>
);
}




function sendMessage(event) {
const messageInput = document.getElementById("messageInput");
const message = messageInput.value;
Expand All @@ -112,6 +108,16 @@ export default function Chat() {
console.error('Unable to copy text: ', err);
});
}

function MessageList({ messages }) {
return (
<div>
{messages.map((message, index) => (
<Message key={index} {...message} />
))}
</div>
);
}
return (
<div>
<div className="chat-container">
Expand Down

0 comments on commit 0566d13

Please sign in to comment.