Skip to content

Commit

Permalink
Redux logic with reduxjs/toolkit
Browse files Browse the repository at this point in the history
  • Loading branch information
many-to-one committed Nov 30, 2023
1 parent 1e959f9 commit 531a0e2
Show file tree
Hide file tree
Showing 12 changed files with 270 additions and 275 deletions.
Binary file modified dump.rdb
Binary file not shown.
2 changes: 1 addition & 1 deletion public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
<title>Lister</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
Expand Down
83 changes: 66 additions & 17 deletions src/components/AllUsers.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,17 @@ import axios from 'axios';

import { useDispatch, useSelector } from 'react-redux';
import { setMessages } from '../features/messages/messagesSlice.js';
import { setUser, addUser, removeUser } from '../features/messages/usersSlice.js';


const AllUsers = (params) => {

const [users, setUsers] = useState([])
// const [users, setUsers] = useState([])
const [socket, setSocket] = useState([])
const [incomingRequest, setIncomingRequest] = useState([])
const [selectedUser, setSelectedUser] = useState(null);
const [conversation, setConversation] = useState([]);
const [friend, setFriend] = useState(null)
// const [selectedUser, setSelectedUser] = useState(null);
// const [conversation, setConversation] = useState([]);
// const [friend, setFriend] = useState(null)
const conv_name = 1


Expand All @@ -26,6 +28,9 @@ const AllUsers = (params) => {

const dispatch = useDispatch();
const allMessages = useSelector((state) => state.messages);
const users = useSelector((state) => state.users);
console.log('users before', users)
// setUsers(usersList)

useEffect(() => {
console.log('allMessages', allMessages)
Expand All @@ -48,6 +53,37 @@ const AllUsers = (params) => {
}
}, [])


useEffect(() => {

if ( users.length === 0 ) {
friendList()
}

}, [user])


const friendList = () => {

axios
.get(`${ serverIP }/auth/friends/`, {
headers: {
Authorization: `Bearer ${user.token}`,
}
})
.then((response) => {
dispatch(setUser(response.data.user_data));
console.log('users after', users)
console.log('friends', response.data.user_data)
})
.catch((error) => {
console.log('Error friendsList', error)
// navigate('/login')
})

}


useEffect(() => {

if ( user ) {
Expand All @@ -64,8 +100,15 @@ const AllUsers = (params) => {
if (data.type === 'allUsers') {

console.log('allUsers', data, data.type);
console.log('friendReq', data.incomingFriendRequest);
setUsers(data.users)
console.log('friends_count', data.friends_count.count);

if ( users.length < data.friends_count.count ) {
friendList()
console.log('count < ');
}
// dispatch(setUser(data.users));

// setUsers(data.users)
setIncomingRequest(data.incomingFriendRequest)

} else if (data.type === 'addFriend') {
Expand All @@ -78,16 +121,17 @@ const AllUsers = (params) => {

} else if (data.type === 'confirmRequest') {

console.log('confirmRequest data', data);
setUsers(data.users)
console.log('confirmRequest data', data.user);
// setUser(data.users)
dispatch(addUser(data.user));
// Remove the added user from request list
{data.users.map((user) => {
// {data.user.map((user) => {
setIncomingRequest((prevUsers) => {
// Use the filter method to remove the user with the specified id
const updatedUsers = prevUsers.filter((u) => u.id !== user.id);
const updatedUsers = prevUsers.filter((u) => u.id !== data.user.id);
return updatedUsers;
});
})}
// })}

} else if (data.type === 'blockResponse') {
console.log('blockResponse', data)
Expand Down Expand Up @@ -124,6 +168,11 @@ const AllUsers = (params) => {
console.log('confirmRequest', 'socket OPEN', id)
socket.send(JSON.stringify({type: 'confirmRequest', requestId: id, userId: user.id}));
}
setIncomingRequest((prevUsers) => {
// Use the filter method to remove the user with the specified id
const updatedUsers = prevUsers.filter((u) => u.id !== id);
return updatedUsers;
});
}


Expand Down Expand Up @@ -152,7 +201,7 @@ const AllUsers = (params) => {


const searchUsers = (text) => {
setUsers((prevUsers) => {
setUser((prevUsers) => {
const updatedUsers = prevUsers.filter((u) => u.username.toLowerCase().includes(text.toLowerCase()))
return updatedUsers;
});
Expand All @@ -165,12 +214,12 @@ const AllUsers = (params) => {

{incomingRequest ? (
<div className="user-list-items">
{incomingRequest.map((user) => (
{incomingRequest.map((userR) => (
<IncomingRequest
user={user}
blockUser={() => blockUser(user.id)}
denyRequest={() => denyRequest(user.id)}
confirmRequest={() => confirmRequest(user.id)}
user={userR}
blockUser={() => blockUser(userR.id)}
denyRequest={() => denyRequest(userR.id)}
confirmRequest={() => confirmRequest(userR.id)}
/>
))}
<hr></hr>
Expand Down
155 changes: 88 additions & 67 deletions src/components/Chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,27 @@ import ConfirmationDialog from './ConfirmationDialog.js';
import { useUser } from '../context/userContext.js';
import AddUsersToChat from './AddUsersToChat.js';

import { useDispatch, useSelector } from 'react-redux';
import { addMessage, removeMessage } from '../features/messages/messagesSlice.js';

const Chat = (props) => {

const { user } = useUser();
const navigate = useNavigate();

// Reseived props:
const location = useLocation()
const chat = location.state
const chatID = chat.id

const dispatch = useDispatch();
const allChatMessages = useSelector((state) => state.messages);
const messages = allChatMessages.filter((message) => message.chat_id === chat.id);
console.log('allChatMessages', allChatMessages)

const [data, setData] = useState(null)

const [messages, setMessages] = useState([]);
// const [messages, setMessages] = useState([]);
const [usersPhotos, setUsersPhotos] = useState([]);
const [newMessage, setNewMessage] = useState('');
const [socket, setSocket] = useState(null);
Expand All @@ -33,11 +46,6 @@ const Chat = (props) => {
// const to make a new message been on the bottom of the chat
const chatContainerRef = useRef(null);

// Reseived props:
const location = useLocation()
const chat = location.state
const chatID = chat.id

const nav = useNavigate()


Expand All @@ -62,69 +70,69 @@ const Chat = (props) => {
// ################################################################################################### //


const allMessages = async () => {

axios
.get(
`${serverIP}/allMessages/${chatID}/`,
{
headers: {
Authorization: `Bearer ${user.token}`,
},
}
)
.then((response) => {
console.log('response.data Chat', response.data)
for (const message of response.data.messages) {
const messageObject = {
id: message.id,
username: message.username,
message: message.content,
photo: message.photo,
};
mess.push(messageObject);
}
setMessages(mess)
setChatUsers(response.data.chat.user)
setUsersPhotos(response.data.photos)
console.log('usersPhotos', usersPhotos)
})
.catch((error) => {
console.error('Error fetching conversation data:', error);
if(error.response.status === 403){
nav('/login')
}else if (error.response.status === 404){
nav('/404')
}
});

}
// const allMessages = async () => {

// axios
// .get(
// `${serverIP}/allMessages/${chatID}/`,
// {
// headers: {
// Authorization: `Bearer ${user.token}`,
// },
// }
// )
// .then((response) => {
// console.log('response.data Chat', response.data)
// for (const message of response.data.messages) {
// const messageObject = {
// id: message.id,
// username: message.username,
// message: message.content,
// photo: message.photo,
// };
// mess.push(messageObject);
// }
// setMessages(mess)
// setChatUsers(response.data.chat.user)
// setUsersPhotos(response.data.photos)
// console.log('usersPhotos', usersPhotos)
// })
// .catch((error) => {
// console.error('Error fetching conversation data:', error);
// if(error.response.status === 403){
// nav('/login')
// }else if (error.response.status === 404){
// nav('/404')
// }
// });

// }



// ################################################################################################### //
// ##################################### CONNECT TO THE SOCKET ####################################### //
// ################################################################################################### //


const ws = new WebSocket(`${wsIP}/ws/chat/${chatID}/?userId=${user.id}&token=${user.token}`);

useEffect(() => {

const ws = new WebSocket(`${wsIP}/ws/chat/${chatID}/?userId=${user.id}&token=${user.token}`);
setSocket(ws);
// const ws = new WebSocket(`${wsIP}/ws/chat/${chatID}/?userId=${user.id}&token=${user.token}`);
// setSocket(ws);

if(ws) {
ws.onopen = () => {
console.log('WebSocket connection opened');
allMessages()
};
ws.onclose = () => {
console.log('WebSocket connection closed');
nav('/login');
};
} else {
nav('/login')
}
// if(ws) {
// ws.onopen = () => {
// console.log('WebSocket connection opened');
// // allMessages()
// };
// ws.onclose = () => {
// console.log('WebSocket connection closed');
// nav('/login');
// };
// } else {
// nav('/login')
// }


// Receive data from server via socket
Expand All @@ -134,13 +142,26 @@ const Chat = (props) => {
if (message.type === 'message_deleted') {
console.log('message_deleted', message.id);
// Handle message deletion by filtering out the deleted message
setMessages((prevMessages) => {
const updatedMessages = prevMessages.filter((msg) => msg.id !== message.id);
console.log('updatedMessages', updatedMessages);
return updatedMessages;
});
// setMessages((prevMessages) => {
// const updatedMessages = prevMessages.filter((msg) => msg.id !== message.id);
// console.log('updatedMessages', updatedMessages);
// return updatedMessages;
// });
} else if (message.type == 'added_message') {
setMessages((prevMessages) => [...prevMessages, { id: message.id, message: message.message, username: message.username, photo: message.photo }]);

dispatch(addMessage({
id: message.id,
message: message.message,
username: message.username,
user_id: message.user_id,
unread: message.unread,
photo: message.photo,
chat_id: message.chat_id,
}));

console.log('addMessage');

// setMessages((prevMessages) => [...prevMessages, { id: message.id, message: message.message, username: message.username, photo: message.photo }]);
// scrollToBottom();
} else if (message.type == 'added_users') {
setSelectedUsers((prevMessages) => [...prevMessages, { users: message, }]);
Expand Down Expand Up @@ -178,11 +199,11 @@ const Chat = (props) => {
}
}

// setSocket(ws);
setSocket(ws);

return () => {
if (socket) {
socket.close();
if (ws) {
ws.close();
}
};

Expand Down
Loading

0 comments on commit 531a0e2

Please sign in to comment.