Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PTBC8_Lester Lim #41

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,5 @@
npm-debug.log*
yarn-debug.log*
yarn-error.log*

.env
1,568 changes: 765 additions & 803 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"firebase": "^9.8.0",
"firebase": "^9.23.0",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "5.0.1"
Expand Down
2 changes: 1 addition & 1 deletion src/App.css
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
}

.App-logo {
height: 40vmin;
height: 20vmin;
pointer-events: none;
}

Expand Down
100 changes: 53 additions & 47 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,60 +1,66 @@
import React from "react";
import React, {useState,useEffect} from "react";
import { onChildAdded, push, ref, set } from "firebase/database";
import { database } from "./firebase";
import {ref as storageRef, uploadBytes, getDownloadURL} from 'firebase/storage'
import { database, storage } from "./firebase";
import logo from "./logo.png";
import "./App.css";
import ChatRoom from "./Component/ChatRoom";
import InputForm from "./Component/InputForm";

// Save the Firebase message folder name as a constant to avoid bugs due to misspelling
const DB_MESSAGES_KEY = "messages";
const STORAGE_KEY = "post/images"

class App extends React.Component {
constructor(props) {
super(props);
// Initialise empty messages array in state to keep local state in sync with Firebase
// When Firebase changes, update local state, which will update local UI
this.state = {
messages: [],
};
}
function App () {
// const [state,setState]=useState({
// messages:[],
// name: "",
// messageToSend:"",
// })
// // Note use of array fields syntax to avoid having to manually bind this method to the class
// const writeData = () => {
// const messageListRef = ref(database, DB_MESSAGES_KEY);
// const newMessageRef = push(messageListRef);
// set(newMessageRef, {
// username:state.name,
// messageBody:state.messageToSend,
// date: new Date().toLocaleString(),
// });
// };

componentDidMount() {
const messagesRef = ref(database, DB_MESSAGES_KEY);
// onChildAdded will return data for every child at the reference and every subsequent new child
onChildAdded(messagesRef, (data) => {
// Add the subsequent child to local component state, initialising a new array to trigger re-render
this.setState((state) => ({
// Store message key so we can use it as a key in our list items when rendering messages
messages: [...state.messages, { key: data.key, val: data.val() }],
}));
});
}
// const handleSubmit = (event) =>{
// event.preventDefault(event);
// writeData();
// }

// const handleChange =(e) =>{
// let name = e.target.name;
// let value = e.target.value;
// setState({...state,
// [name]:value,
// })
// console.log(state)
// }
//key in username
//check db if there is such user
//if there is user, load existing messages and display. else create user with empty messages list
//but how to include messages with other users? timestamp?
//display [timestamp] user: message
//for user in session, display with different color bg or left right orientation

// Note use of array fields syntax to avoid having to manually bind this method to the class
writeData = () => {
const messageListRef = ref(database, DB_MESSAGES_KEY);
const newMessageRef = push(messageListRef);
set(newMessageRef, "abc");
};
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1>
Rocketgram Chat App
</h1>

render() {
// Convert messages in state to message JSX elements to render
let messageListItems = this.state.messages.map((message) => (
<li key={message.key}>{message.val}</li>
));
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
{/* TODO: Add input field and add text input as messages in Firebase */}
<button onClick={this.writeData}>Send</button>
<ol>{messageListItems}</ol>
</header>
</div>
);
}
<InputForm/>
<ChatRoom/>
</header>
</div>
);
}

export default App;
55 changes: 55 additions & 0 deletions src/Component/ChatRoom.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import React, {useState,useEffect} from "react";
import { onChildAdded, ref } from "firebase/database";
import { database, storage } from "../firebase";

const DB_MESSAGES_KEY = "messages";

const ChatRoom=()=>{
const [messages,setMessages] = useState([]);

const getMessages = async() =>{
const handleData = (data) => {
setMessages((prevMessages)=>
// console.log(prevMessages)
[
...prevMessages, { key: data.key, val: data.val() },
]
)};
const messagesRef = ref(database, DB_MESSAGES_KEY);
//onChildAdded will return data for every child at the reference and every subsequent new child
onChildAdded(messagesRef, handleData
// (data) => {
// setMessages({
// messages: [...messages,{ key: data.key, val: data.val() }],
// })}
)
console.log("getMessages was ran")
console.log()
};

useEffect(()=>{
getMessages();
console.log("use effect was run")
},[]);


return(
<div style={{display:"flex",backgroundColor:"Azure",justifyContent:"space-between",width:"70vw"}}>
<ul style={{listStyleType:"none",width:"95%"}}>
{messages.length>0?(messages.map((message) => (
<>
<li key={message.key} style={{display:"flex",marginRight:"35px",backgroundColor:"MidnightBlue",borderRadius:"20px",marginBottom:"10px"}}>
<div style={{margin:"0px 10px"}}>
<p style={{fontSize:"15px",alignContent:"flex-start"}}>
[{message.val.date}] </p>
<p style={{fontSize:"24px"}}>{message.val.username}: {message.val.messageBody} </p>
</div>
</li>
</>
))):<p>There are no messages now!</p>}
</ul>
</div>
)
}

export default ChatRoom;
75 changes: 75 additions & 0 deletions src/Component/InputForm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import {React,useState} from 'react';
import { push, ref, set } from "firebase/database";
import { database, storage } from "../firebase";

const DB_MESSAGES_KEY = "messages";

function InputForm(){
const [state,setState]=useState({
name: "",
messageToSend:"",
})

const writeData = () => {
const messageListRef = ref(database, DB_MESSAGES_KEY);
const newMessageRef = push(messageListRef);
set(newMessageRef, {
username:state.name,
messageBody:state.messageToSend,
date: new Date().toLocaleString(),
});
};

const handleSubmit = (event) =>{
event.preventDefault(event);
writeData();
}
const handleNameSubmit = (event) =>{
event.preventDefault(event);
setState({...state,
displayName:state.name
});
}

const handleChange =(e) =>{
let name = e.target.name;
let value = e.target.value;
setState({...state,
[name]:value,
})
console.log(state)
}

return(
<>
{state.displayName?<p>Hi {state.displayName}! Start Chatting!</p>:<p>Enter name to start chatting!</p>}


{!state.displayName?
<form>
<input
name="name"
value={state.name}
onChange={(e)=>handleChange(e)}
/>
<button onClick={handleNameSubmit}>Enter Name</button>
</form>
:
<form>
<input
name="messageToSend"
value={state.messageToSend}
onChange={(e)=>handleChange(e)}
/>
<button onClick={handleSubmit}>Send</button>
</form>}
<br/>
</>




)
}

export default InputForm;
19 changes: 10 additions & 9 deletions src/firebase.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
import {getStorage} from 'firebase/storage';

// TODO: Replace with your app's Firebase project configuration
// TODO: Configure with .env file later
const firebaseConfig = {
apiKey: "API_KEY",
authDomain: "PROJECT_ID.firebaseapp.com",
// The value of `databaseURL` depends on the location of the database
databaseURL: "https://DATABASE_NAME.REGION.firebasedatabase.app",
projectId: "PROJECT_ID",
storageBucket: "PROJECT_ID.appspot.com",
messagingSenderId: "SENDER_ID",
appId: "APP_ID",
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_APP_ID,
databaseURL: process.env.REACT_APP_DATABASE_URL
};

// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);

// Get a reference to the database service and export the reference for other modules
export const database = getDatabase(firebaseApp);
export const storage = getStorage(firebaseApp);