Skip to content

Commit

Permalink
Merge pull request #96 from Chat-Your-Way/CHAT-236-Interface-for-non-…
Browse files Browse the repository at this point in the history
…authenticated-user

Changed settings of query for refetch onFocus, and by time - since we…
  • Loading branch information
PDigitator authored Jul 10, 2024
2 parents 57f4818 + f07993c commit 49414bf
Show file tree
Hide file tree
Showing 13 changed files with 148 additions and 65 deletions.
2 changes: 1 addition & 1 deletion src/common/Topics/ChatsBlock/ChatItem/ChatItem.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const ChatItem = ({ isActive, data }) => {
const unreadedMessages = data?.unreadMessageCount ?? null;
const lastMessageContent = data?.lastMessage ?? null;

const isTablet = useMediaQuery({ query: '(min-width: 769px' });
const isTablet = useMediaQuery({ query: '(min-width: 768px' });

return (
<StyledBox
Expand Down
23 changes: 16 additions & 7 deletions src/common/Topics/ChatsBlock/ChatsBlock.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,25 @@ import {
} from '../../../redux/authOperatonsToolkit/authOperationsThunkSlice';
// eslint-disable-next-line max-len
import { selectAccessToken } from '../../../redux/authOperatonsToolkit/authOperationsThunkSelectors';
import localLogOutUtil from '../../../utils/localLogOutUtil';

const ChatsBlock = ({ filter }) => {
const { isTopics } = useTopicsContext();
const ChatItems = ChatBlockDataHelper(isTopics); //?!
const { pathname } = useLocation();
const path = pathname.includes('topics') ? 'topics' : 'notification';
const accessTokenInStore = useSelector(selectAccessToken);
const { data, isLoading, isError, error } = useGetAllQuery({
filter,
accessTokenInStore,
});
const { data, isLoading, isError, error } = useGetAllQuery(
{
filter,
accessTokenInStore,
},
{
refetchOnMountOrArgChange: 5,
refetchOnFocus: true,
refetchOnReconnect: true,
},
);
const { localLogOut } = useUser();
const navigate = useNavigate();
const dispatch = useDispatch();
Expand All @@ -43,9 +51,10 @@ const ChatsBlock = ({ filter }) => {

if (error) {
alert('Виникла помилка під час отримання тем (ChatsBlock)');
dispatch(setIsLoggedIn(false));
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
localLogOutUtil(dispatch);
// dispatch(setIsLoggedIn(false));
// localStorage.removeItem('accessToken');
// localStorage.removeItem('refreshToken');
}

return isLoading ? (
Expand Down
26 changes: 15 additions & 11 deletions src/components/Chat/Chat.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ import {
subscribeToMessages,
unsubscribeFromMessages,
getTopicHistory,
sendMessage,
connectWebSocket,
sendMessageByWs,
} from '../../redux/chat-operations';

import { Avatars } from '../../ui-kit/images/avatars';
Expand Down Expand Up @@ -75,6 +75,7 @@ import {
useSendMessageToTopicMutation,
} from '../../redux/messagesAPI/messagesAPI';
import { selectAccessToken } from '../../redux/authOperatonsToolkit/authOperationsThunkSelectors';
import localLogOutUtil from '../../utils/localLogOutUtil';

const Chat = ({ children }) => {
const { title: topicId } = useParams();
Expand All @@ -89,8 +90,9 @@ const Chat = ({ children }) => {
data: messagesByTopic,
currentData: currentMessagesByTopic,
isFetching,
error: messagesByTopicError,
} = useGetMessagesByTopicQuery(topicId, {
refetchOnMountOrArgChange: true,
refetchOnMountOrArgChange: 5,
refetchOnFocus: true,
refetchOnReconnect: true,
});
Expand Down Expand Up @@ -130,7 +132,7 @@ const Chat = ({ children }) => {
dispatch(clearNotifications());

// dispatch(toggleChatOpened());
dispatch(setChatOpened(true));
dispatch(setChatOpened(false));
};

// eslint-disable-next-line react-hooks/exhaustive-deps
Expand Down Expand Up @@ -180,19 +182,21 @@ const Chat = ({ children }) => {
currentMessagesByTopic,
]);

if (isError || sendMessageError) {
if (sendMessageError.data?.message.includes('subscribed to the topic')) {
if (isError || sendMessageError || messagesByTopicError) {
if (sendMessageError?.data?.message?.includes('subscribed to the topic')) {
return alert(
'Потрібно підписатись на цю тему, щоб відправляти повідомлення',
);
}

alert('Виникла помилка під час отримання теми (ChatComponent)');

dispatch(setIsLoggedIn(false));
dispatch(setAccessToken(null));
dispatch(setRefreshToken(null));
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
localLogOutUtil(dispatch);
// dispatch(setIsLoggedIn(false));
// dispatch(setAccessToken(null));
// dispatch(setRefreshToken(null));
// localStorage.removeItem('accessToken');
// localStorage.removeItem('refreshToken');
}

const handleContacts = () => {
Expand All @@ -206,7 +210,7 @@ const Chat = ({ children }) => {
return alert('This message is empty');

if (connected) {
// dispatch(sendMessage(topicId, inputMessage));
// dispatch(sendMessageByWs({ topicId, inputMessage }));
sendMessageToTopic({ topicId, inputMessage, accessTokenInStore });
inputRef.current.value = '';
} else {
Expand Down
11 changes: 6 additions & 5 deletions src/components/Chat/TopicSettingsMenu/TopicSettingsMenu.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
setIsLoggedIn,
setRefreshToken,
} from '../../../redux/authOperatonsToolkit/authOperationsThunkSlice';
import localLogOutUtil from '../../../utils/localLogOutUtil';

const TopicSettingsMenu = ({ topicId, subscribeStatus }) => {
const [anchorEl, setAnchorEl] = useState(null);
Expand All @@ -50,10 +51,10 @@ const TopicSettingsMenu = ({ topicId, subscribeStatus }) => {
alert(
'Виникла помилка під час отримання улюблених тем, авторизуйтесь в системмі!',
);

dispatch(setIsLoggedIn(false));
dispatch(setAccessToken(null));
return dispatch(setRefreshToken(null));
localLogOutUtil(dispatch);
// dispatch(setIsLoggedIn(false));
// dispatch(setAccessToken(null));
// return dispatch(setRefreshToken(null));
}
}

Expand All @@ -69,7 +70,7 @@ const TopicSettingsMenu = ({ topicId, subscribeStatus }) => {

const handleAddFavourite = async () => {
try {
const { error } = await addFavourite(topicId);
const { error } = await addFavourite({ topicId, accessTokenInStore });
if (error) {
alert('Виникла помилка під час додання теми до улюблених');
} else {
Expand Down
25 changes: 22 additions & 3 deletions src/components/Layouts/Footer/Footer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@ import { FooterWrap, LogOutButton, LogOutIcon } from './Footer.styled';
// import { PATH } from '../../../constans/routes';
import { useDispatch, useSelector } from 'react-redux';
import { selectIsLoggedIn } from '../../../redux/authOperatonsToolkit/authOperationsThunkSelectors';
import { setIsLoggedIn } from '../../../redux/authOperatonsToolkit/authOperationsThunkSlice';
// import {
// setAccessToken,
// setIsLoggedIn,
// setRefreshToken,
// } from '../../../redux/authOperatonsToolkit/authOperationsThunkSlice';
// import { setConnected } from '../../../redux/chatSlice';
// import { client } from '../../../redux/chat-operations';
import localLogOutUtil from '../../../utils/localLogOutUtil';

const Footer = () => {
// const { isAuthenticated, localLogOut } = useUser();
Expand All @@ -22,10 +29,22 @@ const Footer = () => {

if (error) {
alert(error.data.message);
dispatch(setIsLoggedIn(false));
// dispatch(setIsLoggedIn(false));
// dispatch(setConnected(false));
// dispatch(setAccessToken(null));
// dispatch(setRefreshToken(null));
// client.deactivate();
localLogOutUtil(dispatch);

return;
}

localLogOutUtil(dispatch);
// dispatch(setIsLoggedIn(false));
// dispatch(setAccessToken(null));
// dispatch(setConnected(false));
// dispatch(setAccessToken(null));
// dispatch(setRefreshToken(null));
// client.deactivate();
// localLogOut();
// navigate(PATH.MAIN);
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ import {
UserInfoBlock,
UserName,
} from './HeaderUserInfo.styled';
import { setIsLoggedIn } from '../../../../redux/authOperatonsToolkit/authOperationsThunkSlice';
// eslint-disable-next-line max-len
import { selectAccessToken } from '../../../../redux/authOperatonsToolkit/authOperationsThunkSelectors';
import localLogOutUtil from '../../../../utils/localLogOutUtil';
// import { selectUserThunk } from '../../../../redux/userApiThunk/userApiThunkSelectors';
// import { useUser } from '../../../../hooks/useUser';
// import { useNavigate } from 'react-router-dom';
Expand Down Expand Up @@ -53,9 +53,7 @@ const HeaderUserInfo = () => {
alert(
'Сталася помилка при отриманні інформації про користувача - необхідно авторизуватись',
);
dispatch(setIsLoggedIn(false));
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
localLogOutUtil(dispatch);
}
// localLogOut();
// navigate(PATH.MAIN);
Expand Down
4 changes: 3 additions & 1 deletion src/components/LoginPageComponent/LoginPageComponent.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ function LoginPageComponent() {
} else if (error.data) {
alert(error.data.message);
} else {
alert('Something goes wrong :-( Maybe server is down.');
alert(
'Something goes wrong :-( Maybe server or your connection is down.',
);
}
return;
}
Expand Down
25 changes: 22 additions & 3 deletions src/hooks/useWebSocketConnection.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,43 @@ import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { client } from '../redux/chat-operations';
import { selectConnected, setConnected } from '../redux/chatSlice';
// import { connectWebSocket } from '../redux/chat-operations';
import SockJS from 'sockjs-client';
import { selectAccessToken } from '../redux/authOperatonsToolkit/authOperationsThunkSelectors';
import { BASE_URL } from '../redux/apiParams';
import localLogOutUtil from '../utils/localLogOutUtil';

export const useWebSocketConnection = (isLoggedIn) => {
const dispatch = useDispatch();
const connected = useSelector(selectConnected);
const stompClient = client;
const accessTokenInStore = useSelector(selectAccessToken);

useEffect(() => {
if (isLoggedIn && !connected) {
// dispatch(connectWebSocket());
const socket = new SockJS(
`${BASE_URL}/chat?Authorization=Bearer ${accessTokenInStore}`,
);

stompClient.activate();
stompClient.configure({
socket.onmessage = function () {
// I think it don't work.
};

client.configure({
onConnect: (frame) => {
if (frame.command === 'CONNECTED') {
dispatch(setConnected(true));
}
},
onWebSocketError: () => {
localLogOutUtil(dispatch);
},
webSocketFactory: function () {
return socket;
},
});

client.activate();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
Expand Down
6 changes: 4 additions & 2 deletions src/pages/TopicsPage/TopicsPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ import { useTopicsPageContext } from './TopicsPageContext';
import { useTopicsContext } from '../../common/Topics/TopicsContext';

const useTabletAndBelowMediaQuery = () =>
useMediaQuery({ query: '(max-width: 770px)' });
// useMediaQuery({ query: '(max-width: 770px)' });
useMediaQuery({ query: '(max-width: 768px)' });

const useMobileMediaQuery = () =>
useMediaQuery({ query: '(max-width: 769px)' });
// useMediaQuery({ query: '(max-width: 769px)' });
useMediaQuery({ query: '(max-width: 767px)' });

function TopicsPage() {
const isTabletAndBelow = useTabletAndBelowMediaQuery();
Expand Down
Loading

0 comments on commit 49414bf

Please sign in to comment.