Skip to content

Commit

Permalink
updated firestore
Browse files Browse the repository at this point in the history
  • Loading branch information
Ethemkizilyer committed Jul 4, 2024
1 parent 78e8dbd commit a6baaf9
Show file tree
Hide file tree
Showing 18 changed files with 211 additions and 141 deletions.
1 change: 0 additions & 1 deletion src/App.js → src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import logo from "./logo.svg";
import "./style.scss";
import Register from "./pages/Register";
import Login from "./pages/Login";
Expand Down
2 changes: 1 addition & 1 deletion src/components/Chat.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const Chat = () => {
return (
<div className="chat">
<div className="chatInfo">
<span>{data?.user?.displayName}</span>
<span>{data?.user?.username}</span>
<div className="chatIcons">
<BsCameraVideo />
<BiUserPlus />
Expand Down
23 changes: 11 additions & 12 deletions src/components/Chats.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,31 @@ const Chats = () => {
const {currentUser}= useContext(Context)
const { dispatch } = useContext(ChatContext);
useEffect(()=> {
const getChats=()=>{
const unsub=onSnapshot(doc(db,"userChats",currentUser?.uid),(doc)=> {
setchats(doc?.data())
console.log("Current data:",doc?.data())
const unsub=onSnapshot(doc(db,"userchats",currentUser?.id),(res)=> {
setchats(res?.data())
console.log("Current data:",res?.data())
})

console.log(unsub())

return ()=> {
unsub();
};}
currentUser.uid && getChats()
},[currentUser?.uid])
};
},[currentUser?.id])
console.log(Object?.entries(chats));
// console.log(chats);
console.log(chats);
console.log(currentUser);

const handleSelect=(u)=>{
dispatch({type:"CHANGE_USER",payload:u})
}

return (
<div className="chats">
{Object?.entries(chats)?.sort((a,b)=>b[1].date-a[1].date).map((chat) => (
{Object?.entries(chats)?.sort((a,b)=>b[1].date-a[1]?.date)?.map((chat) => (
<div className="userChat" key={chat[0]} onClick={()=>handleSelect(chat[1]?.userInfo)}>
<img src={chat[1]?.userInfo.photoURL} alt="" />
<img src={chat[1]?.userInfo.avatar} alt="" />
<div className="userChatInfo">
<span>{chat[1]?.userInfo.displayName}</span>
<span>{chat[1]?.userInfo.username}</span>
<p>{chat[1]?.lastMessage?.text}</p>
</div>
</div>
Expand Down
10 changes: 5 additions & 5 deletions src/components/Input.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const Input = () => {
const [img, setImg] = useState(null);
const { currentUser } = useContext(Context);
const { data } = useContext(ChatContext);

console.log(data)
const handleSend = async () => {
if (img) {
const storageRef = ref(storage, uuid());
Expand All @@ -30,7 +30,7 @@ const Input = () => {
messages: arrayUnion({
id: uuid(),
text,
senderId: currentUser.uid,
senderId: currentUser.id,
date: Timestamp.now(),
img: downloadURL,
}),
Expand All @@ -43,19 +43,19 @@ const Input = () => {
messages: arrayUnion({
id: uuid(),
text,
senderId: currentUser.uid,
senderId: currentUser.id,
date: Timestamp.now(),
}),
});
}

await updateDoc(doc(db,"userChats",currentUser.uid),{
await updateDoc(doc(db,"userchats",currentUser.id),{
[data.chatId + ".lastMessage"]:{
text
},
[data.chatId+".date"]:serverTimestamp()
})
await updateDoc(doc(db,"userChats",data.user.uid),{
await updateDoc(doc(db,"userchats",data.user.uid),{
[data.chatId + ".lastMessage"]:{
text
},
Expand Down
6 changes: 3 additions & 3 deletions src/components/Message.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,14 @@ const Message = ({ message }) => {

return (
<div
className={`message ${message.senderId === currentUser.uid && "owner"}`}
className={`message ${message.senderId === currentUser.id && "owner"}`}
>
<div className="messageInfo">
<img
src={
message.senderId === currentUser.uid
? currentUser.photoURL
: data.user.photoURL
? currentUser.avatar
: data.user.avatar
}
alt=""
/>
Expand Down
4 changes: 2 additions & 2 deletions src/components/Navbar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ const Navbar = () => {
<div className="user">
<img
src=
{currentUser?.photoURL}
{currentUser?.avatar}

alt=""
/>
<span>{currentUser?.displayName}</span>
<span>{currentUser?.username}</span>
<button onClick={()=>{
navigate("/login")
signOut(auth)}}>Logout</button>
Expand Down
31 changes: 16 additions & 15 deletions src/components/Search.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,10 @@ const Search = () => {
const handleSearch = async () => {
const q = query(
collection(db, "users"),
where("displayName", "==", username)
where("username", "==", username)
);

const asd = await getDocs(q);
console.log(asd)
try {
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
Expand All @@ -49,9 +50,9 @@ const Search = () => {
const handleSelect = async () => {
// group mesajı firestore da var mı yok mu kontrol için eğer yoksa 1 tane oluştur
const combinedId =
currentUser.uid > user.uid
? currentUser.uid + user.uid
: user.uid + currentUser.uid;
currentUser.id > user.id
? currentUser.id + user.id
: user.uid + currentUser.id;
try {
const res = await getDoc(doc(db, "chats", combinedId));

Expand All @@ -60,21 +61,21 @@ const Search = () => {
await setDoc(doc(db, "chats", combinedId), { messages: [] });

//Kullanıcı sohbetleri oluşturulacak
await updateDoc(doc(db, "userChats", currentUser.uid), {
await updateDoc(doc(db, "userchats", currentUser.id), {
[combinedId + ".userInfo"]: {
uid: user.uid,
displayName: user.displayName,
photoURL: user.photoURL,
id: user.id,
username: user.username,
avatar: user.avatar,
},
[combinedId + ".date"]: serverTimestamp(),
});

//Buda diğer kullanıcı için
await updateDoc(doc(db, "userChats", user.uid), {
await updateDoc(doc(db, "userchats", user.id), {
[combinedId + ".userInfo"]: {
uid: currentUser.uid,
displayName: currentUser.displayName,
photoURL: currentUser.photoURL,
id: currentUser.id,
displayName: currentUser.username,
avatar: currentUser.avatar,
},
[combinedId + ".date"]: serverTimestamp(),
});
Expand All @@ -100,9 +101,9 @@ const Search = () => {
{err && <span>User not found</span>}
{user && (
<div className="userChat" onClick={handleSelect}>
<img src={user?.photoURL} alt="" />
<img src={user?.avatar} alt="" />
<div className="userChatInfo">
<span>{user?.displayName}</span>
<span>{user?.username}</span>
</div>
</div>
)}
Expand Down
14 changes: 11 additions & 3 deletions src/context/AuthContext.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { onAuthStateChanged } from "firebase/auth";
import { createContext, useEffect, useState } from "react";
import { auth } from "../firebase";
import { auth, db } from "../firebase";
import { doc, getDoc } from "firebase/firestore";


export const Context= createContext();
Expand All @@ -9,10 +10,17 @@ export const ContextProvider=({children})=>{
const [currentUser,setCurrentUser]=useState({});

useEffect(()=>{
onAuthStateChanged(auth,(user)=> {
setCurrentUser(user);
onAuthStateChanged(auth, async(user)=> {
const docRef=doc(db,"users",user.uid)
const docSnap = await getDoc(docRef)

if(docSnap.exists()){
setCurrentUser(docSnap.data());
}

console.log(user)
})

},[])

return (
Expand Down
4 changes: 2 additions & 2 deletions src/context/ChatContext.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ export const ChatContextProvider = ({ children }) => {
chatId:"null",
user:{}
}

console.log(currentUser)
const chatReducer=(state,action)=> {
switch (action.type){
case "CHANGE_USER":
return {
user:action.payload,
chatId:
currentUser.uid > action.payload.uid ? currentUser.uid + action.payload.uid : action.payload.uid + currentUser.uid,
currentUser.id > action.payload.uid ? currentUser.id + action.payload.uid : action.payload.uid + currentUser.id,
};

default:
Expand Down
24 changes: 0 additions & 24 deletions src/firebase.js

This file was deleted.

20 changes: 20 additions & 0 deletions src/firebase.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";


const firebaseConfig = {
apiKey: "AIzaSyA1gcZnkWzxLPvFNGyU5y19vm9BmLZySHQ",
authDomain: "reactchats-75f4e.firebaseapp.com",
projectId: "reactchats-75f4e",
storageBucket: "reactchats-75f4e.appspot.com",
messagingSenderId: "638499853955",
appId: "1:638499853955:web:6197a464dbab11eb70adb6"
};

// Initialize Firebase
export const app = initializeApp(firebaseConfig);
export const auth = getAuth();
export const storage = getStorage();
export const db=getFirestore()
1 change: 0 additions & 1 deletion src/logo.svg

This file was deleted.

52 changes: 35 additions & 17 deletions src/pages/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,38 @@ import { auth } from "../firebase";
const Login = () => {
const [err, setErr] = useState(false);
const navigate= useNavigate()
const [loginEmail, setLoginEmail] = useState("");
const [loginPassword, setLoginPassword] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");

const handleSubmit=async(e)=>{
e.preventDefault()
try{
const user= await signInWithEmailAndPassword(auth,loginEmail,loginPassword);
navigate(-1)
alert("Hoşgeldin")
} catch(err){
// alert(err.message)
setErr(true)
}
}
const handleSubmit = async (e) => {
e.preventDefault();
try {
const res= await signInWithEmailAndPassword(auth, email, password)
.then((user) => {
console.log("user",user)
navigate("/");
alert("Hoşgeldin")
})
.catch((error) => {
const errorCode = error.code;
console.log(errorCode);

if (errorCode === 'auth/user-not-found') {
console.log("Account doesn't exist.");
} else if (errorCode === 'auth/wrong-password') {
console.log('Invalid password.');
} else {
console.log('Something went wrong.');
}
})
.finally(() => {
console.log(false);
});
} catch (err) {
console.error(err.code, err.message);
setErr(true);
}
};



Expand All @@ -34,14 +52,14 @@ const handleSubmit=async(e)=>{
<input
type="email"
placeholder="email"
value={loginEmail}
onChange={(e) => setLoginEmail(e.target.value)}
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="password"
placeholder="password"
value={loginPassword}
onChange={(e) => setLoginPassword(e.target.value)}
value={password}
onChange={(e) => setPassword(e.target.value)}
/>

<button onClick={handleSubmit}>Sign in</button>
Expand Down
Loading

0 comments on commit a6baaf9

Please sign in to comment.