0% found this document useful (0 votes)
7 views26 pages

Firebase Merged

The document outlines a chat application built using Firebase, React, and Material-UI, featuring user authentication, sign-up, and chat functionalities. It includes components for signing in, signing up, and displaying chat messages, as well as managing user data in Firestore. Future enhancements for the application are suggested, indicating potential for further development and features.

Uploaded by

userdumb709
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views26 pages

Firebase Merged

The document outlines a chat application built using Firebase, React, and Material-UI, featuring user authentication, sign-up, and chat functionalities. It includes components for signing in, signing up, and displaying chat messages, as well as managing user data in Firestore. Future enhancements for the application are suggested, indicating potential for further development and features.

Uploaded by

userdumb709
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Firebase.

js

import { initializeApp } from "firebase/app";

import { getFirestore } from "firebase/firestore";

import { getAuth } from "firebase/auth";

const firebaseConfig = {

apiKey: "AIzaSyBpmX4IAa3TSjgOySyEsfIUIoc_zZyJouo",

authDomain: "my-vue-app-64fa3.firebaseapp.com",

projectId: "my-vue-app-64fa3",

storageBucket: "my-vue-app-64fa3.firebasestorage.app",

messagingSenderId: "448636428034",

appId: "1:448636428034:web:2e2792b58e369dcd966c1b",

measurementId: "G-LGTYT6H641"

};

const app = initializeApp(firebaseConfig);

const db = getFirestore(app);

const auth = getAuth(app);

export { db, auth };


App.jsx

import "./App.css";

import { BrowserRouter, Routes, Route }

from "react-router-dom";

import SignIn from "./Screens/Signin";

import SignUp from "./Screens/Signup";

import ChatHome from "./Screens/ChatHome";

function App() {

return (

<div className="App">

<BrowserRouter>

<Routes>

<Route exact path="/"

element={<SignIn />} />

<Route path="/Signup"

element={<SignUp />} />

<Route path="/chat-home/:receiverId"

element={<ChatHome />} />

</Routes>

</BrowserRouter>

</div>

);

export default App;


SignUp.jsx

import * as React from "react";

import Avatar from "@mui/material/Avatar";

import Button from "@mui/material/Button";

import CssBaseline from "@mui/material/CssBaseline";

import TextField from "@mui/material/TextField";

import Link from "@mui/material/Link";

import Grid from "@mui/material/Grid";

import Box from "@mui/material/Box";

import LockOutlinedIcon from "@mui/icons-material/LockOutlined";

import Typography from "@mui/material/Typography";

import Container from "@mui/material/Container";

import { createTheme, ThemeProvider } from "@mui/material/styles";

import { auth, db } from "../firebase";

import {

createUserWithEmailAndPassword,

updateProfile

} from "firebase/auth";

import { doc, setDoc } from "firebase/firestore";

import { useNavigate } from "react-router-dom";

function Copyright(props) {

return (

<Typography

variant="body2"

color="text.secondary"

align="center"

{...props}

>

{"Copyright © "}

<Link color="inherit" href="https://mui.com/">

Your Website
</Link>{" "}

{new Date().getFullYear()}

{"."}

</Typography>

);

const theme = createTheme();

export default function SignUp() {

const [username, setUsername] = React.useState("");

const [email, setEmail] = React.useState("");

const [password, setPassword] = React.useState("");

const navigate = useNavigate();

const handleSubmit = async (event) => {

event.preventDefault();

try {

const userCredential = await createUserWithEmailAndPassword(

auth,

email,

password

);

const update = await updateProfile(auth.currentUser, {

displayName: username,

});

const user = userCredential.user;

setDoc(doc(db, "users", user.uid), {


username: username,

email: email,

userId: user.uid,

timestamp: new Date(),

});

navigate("/");

} catch (error) {

alert(error.message);

};

return (

<ThemeProvider theme={theme}>

<Container component="main" maxWidth="xs">

<CssBaseline />

<Box

sx={{

marginTop: 8,

display: "flex",

flexDirection: "column",

alignItems: "center",

}}

>

<Avatar sx={{ m: 1, bgcolor: "secondary.main" }}>

<LockOutlinedIcon />

</Avatar>

<Typography component="h1" variant="h5">

Sign up

</Typography>

<Box
component="form"

noValidate

onSubmit={handleSubmit}

sx={{ mt: 3 }}

>

<Grid container spacing={2}>

<Grid item xs={12}>

<TextField

autoComplete="given-name"

name="firstName"

required

fullWidth

id="firstName"

label="First Name"

autoFocus

value={username}

onChange={(e) => setUsername(e.target.value)}

/>

</Grid>

<Grid item xs={12}>

<TextField

required

fullWidth

id="email"

label="Email Address"

name="email"

autoComplete="email"

value={email}

onChange={(e) => setEmail(e.target.value)}

/>
</Grid>

<Grid item xs={12}>

<TextField

required

fullWidth

name="password"

label="Password"

type="password"

id="password"

autoComplete="new-password"

value={password}

onChange={(e) => setPassword(e.target.value)}

/>

</Grid>

</Grid>

<Button

type="submit"

fullWidth

variant="contained"

sx={{ mt: 3, mb: 2 }}

>

Sign Up

</Button>

<Grid container justifyContent="flex-end">

<Grid item>

<Link href="/" variant="body2">

Already have an account? Sign in

</Link>

</Grid>

</Grid>

</Box>
</Box>

<Copyright sx={{ mt: 5 }} />

</Container>

</ThemeProvider>

);

}
Signin.jsx

import * as React from "react";

import Avatar from "@mui/material/Avatar";

import Button from "@mui/material/Button";

import CssBaseline from "@mui/material/CssBaseline";

import TextField from "@mui/material/TextField";

import FormControlLabel from "@mui/material/FormControlLabel";

import Checkbox from "@mui/material/Checkbox";

import Link from "@mui/material/Link";

import Grid from "@mui/material/Grid";

import Box from "@mui/material/Box";

import LockOutlinedIcon from "@mui/icons-material/LockOutlined";

import Typography from "@mui/material/Typography";

import Container from "@mui/material/Container";

import { createTheme, ThemeProvider } from "@mui/material/styles";

import { useNavigate } from "react-router-dom";

import { signInWithEmailAndPassword } from "firebase/auth";

import { auth } from "../firebase";

const theme = createTheme();

export default function SignIn() {

const [email, setEmail] = React.useState("");

const [password, setPassword] = React.useState("");

const navigate = useNavigate();

const handleSubmit = async (event) => {

event.preventDefault();

signInWithEmailAndPassword(auth, email, password)

.then((userCredential) => {

// Signed in
const user = userCredential.user;

navigate("/chat-home/1");

// ...

})

.catch((error) => {

const errorCode = error.code;

const errorMessage = error.message;

alert(errorMessage);

});

};

return (

<ThemeProvider theme={theme}>

<Container component="main" maxWidth="xs">

<CssBaseline />

<Box

sx={{

marginTop: 8,

display: "flex",

flexDirection: "column",

alignItems: "center",

}}

>

<Avatar sx={{ m: 1, bgcolor: "secondary.main" }}>

<LockOutlinedIcon />

</Avatar>

<Typography component="h1" variant="h5">

Sign in

</Typography>
<Box

component="form"

onSubmit={handleSubmit}

noValidate

sx={{ mt: 1 }}

>

<TextField

margin="normal"

required

fullWidth

id="email"

label="Email Address"

name="email"

autoComplete="email"

autoFocus

value={email}

onChange={(e) => setEmail(e.target.value)}

/>

<TextField

margin="normal"

required

fullWidth

name="password"

label="Password"

type="password"

id="password"

autoComplete="current-password"

value={password}

onChange={(e) => setPassword(e.target.value)}

/>

<FormControlLabel
control={<Checkbox value="remember"

color="primary" />}

label="Remember me"

/>

<Button

type="submit"

fullWidth

variant="contained"

sx={{ mt: 3, mb: 2 }}

>

Sign In

</Button>

<Grid container>

<Grid item xs>

<Link href="#" variant="body2">

Forgot password?

</Link>

</Grid>

<Grid item>

<Link href="/Signup" variant="body2">

{"Don't have an account? Sign Up"}

</Link>

</Grid>

</Grid>

</Box>

</Box>

</Container>

</ThemeProvider>

);

}
Chathome.jsx

import React, { useEffect, useState } from "react";

import Paper from "@mui/material/Paper";

import { Button, Divider, IconButton } from "@mui/material";

import SendIcon from "@mui/icons-material/Send";

import List from "@mui/material/List";

import ListItem from "@mui/material/ListItem";

import ListItemButton from "@mui/material/ListItemButton";

import ListItemText from "@mui/material/ListItemText";

import ListItemAvatar from "@mui/material/ListItemAvatar";

import Avatar from "@mui/material/Avatar";

import { useNavigate } from "react-router";

import { db, auth } from "../Firebase";

import {

addDoc,

collection,

onSnapshot,

orderBy,

query,

} from "firebase/firestore";

function UsersComponent(props) {

const handleToggle = (username, userId) => {

props.setReceiverData({

username: username,

userId: userId,

});

props.navigate(`/chat-home/${userId}`);

};
Chathome.jsx

return (

<List

dense

sx={{

width: "100%", maxWidth: 360,

bgcolor: "background.paper"

}}

>

{props.users?.map((value, index) => {

const labelId = `checkbox-list-secondary-label-${value}`;

if (props.currentUserId !== value.userId)

return (

<ListItem key={value.userId} disablePadding>

<ListItemButton

onClick={() => {

handleToggle(value.username, value.userId);

}}

>

<ListItemAvatar>

<Avatar

alt={`${value.username}`}

src={`${value.username}.jpg`}

/>

</ListItemAvatar>

<ListItemText id={labelId}

primary={`${value.username}`} />

</ListItemButton>

</ListItem>

);

})}
Chathome.jsx

</List>

);

export default function Home() {

const [users, setUsers] = useState([]);

const [receiverData, setReceiverData] = useState(null);

const [chatMessage, setChatMessage] = useState("");

const [allMessages, setAllMessages] = useState([]);

const user = auth.currentUser;

const navigate = useNavigate();

useEffect(() => {

const unsub = onSnapshot(collection(db, "users"), (snapshot) => {

setUsers(snapshot.docs.map((doc) => doc.data()));

});

return unsub;

}, []);

useEffect(() => {

if (receiverData) {

const unsub = onSnapshot(

query(

collection(

db,

"users",

user?.uid,
Chathome.jsx

"chatUsers",

receiverData?.userId,

"messages"

),

orderBy("timestamp")

),

(snapshot) => {

setAllMessages(

snapshot.docs.map((doc) => ({

id: doc.id,

messages: doc.data(),

}))

);

);

return unsub;

}, [receiverData?.userId]);

const sendMessage = async () => {

try {

if (user && receiverData) {

await addDoc(

collection(

db,

"users",

user.uid,

"chatUsers",

receiverData.userId,

"messages"

),
Chathome.jsx

username: user.displayName,

messageUserId: user.uid,

message: chatMessage,

timestamp: new Date(),

);

await addDoc(

collection(

db,

"users",

receiverData.userId,

"chatUsers",

user.uid,

"messages"

),

username: user.displayName,

messageUserId: user.uid,

message: chatMessage,

timestamp: new Date(),

);

} catch (error) {

console.log(error);

setChatMessage("");

};
Chathome.jsx

return (

<div style={root}>

<Paper style={left}>

<div

style={{

display: "flex",

padding: 5,

justifyContent: "space-between",

}}

>

<h4 style={{ margin: 0 }}>{user?.displayName} </h4>

<Button

color="secondary"

onClick={() => {

auth.signOut();

navigate("/");

}}

>

Logout

</Button>

</div>

<Divider />

All users

<div style={{ overflowY: "scroll" }}>

<UsersComponent

users={users}

setReceiverData={setReceiverData}

navigate={navigate}

currentUserId={user?.uid}

/>

</div>
Chathome.jsx

</Paper>

<Paper style={right}>

<h4 style={{ margin: 2, padding: 10 }}>

{receiverData ? receiverData.username : user?.displayName}{" "}

</h4>

<Divider />

<div style={messagesDiv}>

{/* messages area */}

{allMessages &&

allMessages.map(({ id, messages }) => {

return (

<div

key={id}

style={{

margin: 2,

display: "flex",

flexDirection:

user?.uid == messages.messageUserId

? "row-reverse"

: "row",

}}

>

<span

style={{

backgroundColor: "#BB8FCE",

padding: 6,

borderTopLeftRadius:

user?.uid == messages.messageUserId ? 10 : 0,
Chathome.jsx

borderTopRightRadius:

user?.uid == messages.messageUserId ? 0 : 10,

borderBottomLeftRadius: 10,

borderBottomRightRadius: 10,

maxWidth: 400,

fontSize: 15,

textAlign:

user?.uid == messages.messageUserId ? "right" : "left",

}}

>

{messages.message}

</span>

</div>

);

})}

</div>

<div style={{ width: "100%", display: "flex", flex: 0.08 }}>

<input

value={chatMessage}

onChange={(e) => setChatMessage(e.target.value)}

style={input}

type="text"

placeholder="Type message..."

/>

<IconButton onClick={sendMessage}>

<SendIcon style={{ margin: 10 }} />

</IconButton>

</div>

</Paper>

</div>
Chathome.jsx

);

const root = {

display: "flex",

flexDirection: "row",

flex: 1,

width: "100%",

};

const left = {

display: "flex",

flex: 0.2,

height: "95vh",

margin: 10,

flexDirection: "column",

};

const right = {

display: "flex",

flex: 0.8,

height: "95vh",

margin: 10,

flexDirection: "column",

};

const input = {

flex: 1,

outline: "none",

borderRadius: 5,

border: "none",
Chathome.jsx

};

const messagesDiv = {

backgroundColor: "#FBEEE6",

padding: 5,

display: "flex",

flexDirection: "column",

flex: 1,

maxHeight: 460,

overflowY: "scroll",

};
13.FUTURE SCOPE AND FURTHER ENHANCEMENTS

A single message chat application built using the (FireBase,


Express.js, React.js, Node.js) technology stack can be further enhanced
and expanded in several ways to improve its functionality and user
experience. Here are some future scope and further enhancements for
your single message chat application:

Real-time Messaging: Implement real-time messaging using technologies


like Web-Sockets or a library like Socket.IO. This will allow users to see
messages instantly without needing to refresh the page.

User Authentication and Authorization: Enhance the application by


implementing user authentication and authorization mechanisms. This
will enable users to create accounts, log in, and have personalized chat
experiences.

Emoji’s and Reactions: Enable users to express their emotions and


reactions using emoji’s or predefined reactions. Implement a reaction
system similar to social media platforms where users can add emoji’s or
"like" messages.

Mobile Application: Consider developing a mobile application version of


the chat application for both iOS and Android platforms. This can broaden
the user base and provide a seamless mobile chat experience.

47 | P a g e
14.LIMITATIONS

There are several limitations that you may encounter when developing a
single message chat application using the (FireBase, Express.js,
React, Node.js) technology stack. Here are a few potential limitations:

Scalability: The MERN stack can handle moderate levels of traffic and
users, but it may face scalability challenges when dealing with a large
number of concurrent connections or heavy message traffic. Scaling the
application to handle high loads might require implementing techniques
such as load balancing, horizontal scaling, or using a dedicated messaging
service.

Performance: As the number of messages increases, fetching and


rendering all the messages on the client side could lead to performance
issues. It's important to implement pagination or infinite scrolling to limit
the number of messages loaded at a time and optimize the rendering
process.

Security: Security is a critical aspect of any chat application. MERN


provides tools and libraries for handling security concerns, such as
authentication and authorization, but it's essential to ensure that proper
security measures are implemented to protect user data, prevent
unauthorized access, and secure communication channels.

Offline functionality: ReactJs does not natively support offline


functionality. If users need to access the chat application or send
messages while offline, you would need to implement additional
techniques such as client-side caching or using a service worker to handle
offline data synchronization.

Mobile app development: While ReactJs is well-suited for web


applications, if we plan to develop a mobile app version, additional
frameworks or technologies, such as React Native or Flutter, would be
required. This introduces the need for separate codebases and additional
development efforts.
48 | P a g e
15.CONCLUSION

In conclusion, building a single message chat application using the


(Express.js, React.js, Node.js) technology stack provides
several benefits and advantages.

The technology offers a comprehensive solution for developing a chat


application that supports real-time communication. By leveraging web-
sockets or similar technologies, users can instantly exchange messages.

Thes technology supports the creation of cross-platform applications,


allowing users to access the chat application from various devices and
operating systems.

Using JavaScript throughout the entire stack provides a developer-


friendly environment. It reduces the learning curve, promotes code
consistency, and facilitates easier code maintenance.

Thes technology benefits from a large and active community. This means
developers can find extensive resources, tutorials, and libraries to assist
in the development process and troubleshoot any issues.

While considering the advantages of the this tech it's crucial to take
into account the specific requirements and constraints of your project.
Proper planning, architectural considerations, and adherence to best
practices are essential for ensuring a secure, efficient, and user-friendly
single message chat application.

This tech provides a unified and consistent development experience


since JavaScript is used throughout the entire stack. This reduces the
learning curve for developers and allows for easier code maintenance.

49 | P a g e
16.BIBLIOGRAPHY

• React Documentation- Retrieved from https://react.dev/learn

• Node.js Documentation- Retrieved from


https://nodejs.org/en/docs

• Express Documentation- Retrieved from


https://expressjs.com/en/4x/api.html

• FireBase Documentation- Retrieved from


https://docs.firebase.com/manual

• Socket.io Documentation- Retrieved from


https://socket.io/docs/v4

• W3Schools- Retrieved from https://www.w3schools.com

• Emoji Mart- Retrieved from


https://www.npmjs.com/package/emoji-mart

-Thank You

------------X-----------

50 | P a g e

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy