Skip to content

Commit

Permalink
Add test chat
Browse files Browse the repository at this point in the history
  • Loading branch information
jahongiry committed Feb 18, 2024
1 parent 9d7926e commit 501cf87
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 0 deletions.
80 changes: 80 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"react-toastify": "^10.0.4",
"react-use-websocket": "^4.5.0",
"slick-carousel": "^1.8.1",
"socket.io-client": "^4.7.4",
"swiper": "^11.0.5",
"telegraf": "^4.15.3",
"web-vitals": "^2.1.4"
Expand Down
24 changes: 24 additions & 0 deletions src/pages/chat/Chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,31 @@ import './chat.css';
import ChatHeader from './charHeader/chatHeader';
import { fetchChats } from '../../slices/chatSlice';
import { selectCurrentUser } from '../../slices/authSlice';
import io from 'socket.io-client';

const Chat = () => {
const [inputValue, setInputValue] = useState('');
const [socket, setSocket] = useState(null);
const dispatch = useDispatch();
const location = useLocation();
const { selectedChatId, chatUsers } = location.state || {};
const chats = useSelector((state) => state.chat.chats);
const messages = chats[selectedChatId]?.messages || [];
const user = useSelector(selectCurrentUser);
const messagesEndRef = useRef(null);
const token = localStorage.getItem('token');

useEffect(() => {
if (token) {
const newSocket = io('https://cyberswap.uz', {
query: { token: encodeURIComponent(token) },
transports: ['websocket'], // use WebSocket first, fallback to polling if necessary
});
setSocket(newSocket);

return () => newSocket.close();
}
}, [token]);

const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
Expand All @@ -27,10 +42,19 @@ const Chat = () => {
const handleSubmit = (event) => {
event.preventDefault();
if (inputValue.trim()) {
socket.emit('message', { content: inputValue, chat_id: selectedChatId });
setInputValue('');
}
};

useEffect(() => {
if (socket) {
socket.on('message', (newMessage) => {
console.log(newMessage);
});
}
}, [socket]);

const getMessageClass = (message) => {
if (message.content.length <= 20) {
if (message.content.length <= 1) {
Expand Down

0 comments on commit 501cf87

Please sign in to comment.