p.440 ~ 441 메시지 생성 시에 date 오류 문제 #113
Answered
by
Alchemist85K
cocoburger
asked this question in
Q&A
-
메세지 생성 date 오류
//firebase.js
import * as firebase from "firebase/compat";
import config from '../../firebase.json';
import 'firebase/firestore';
import { getFirestore, collection, doc, setDoc } from 'firebase/firestore';
const app = firebase.initializeApp(config);
const Auth = app.auth();
export const DB = firebase.firestore();
export const login = async ({ email, password }) => {
const {user} = await Auth.signInWithEmailAndPassword(email,password);
return user;
}
export const signup = async ({email, password, name, photoUrl }) => {
const {user} = await Auth.createUserWithEmailAndPassword(email, password);
//https의 여부에 따라서 있으면 사용자가 사진을 선택하지 않고 진행한 경우 이므로, (https://firebase)로 시작하고
//선택한 경우에는 (file://) 로 시작하므로 https의 여부에 따라서 있으면 기본 이미지, 없으면 upload를 한다.
const storageUrl = photoUrl.startsWith('https')
? photoUrl
: await uploadImage(photoUrl);
await user.updateProfile({
displayName: name,
photoURL: storageUrl,
});
return user;
};
/**
*
* @param uri
* @returns {Promise<*>}
* 업로드는 promise를 만들어 사용한다.
*/
const uploadImage = async uri => {
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
reject(new TypeError('Network request failed'));
};
xhr.responseType = 'blob';
xhr.open('GET', uri, true);
xhr.send(null);
});
const user = Auth.currentUser;
const ref = app.storage().ref(`/profile/${user.uid}/photo.png`);
const snapshot = await ref.put(blob, {contentType:'image/png' });
blob.close();
return await snapshot.ref.getDownloadURL();
};
export const logout = async () => {
return await Auth.signOut();
}
export const getCurrentUser = () => {
const {uid, displayName, email, photoURL} = Auth.currentUser;
return {uid, name: displayName, email, photoURL: photoURL};
};
export const updateUserPhoto = async photoUrl => {
const user = Auth.currentUser;
const storageUrl = photoUrl.startsWith('https')
? photoUrl
: await uploadImage(photoUrl);
await user.updateProfile({photoURL : storageUrl });
return { name: user.displayName, email:user.email, photoUrl: user.photoUrl };
}
// collection에서 문서를 생성할 때 id를 지정하지 않으면, firestore에서 자동으로 중복되지 않는 id를 생성해 문서의 id로 사용한다.
// 자동으로 생성된 문서의 id는 뭔서의 필드로도 저장하고, 사용자에게 입력받은 채널의 제목과 설명을 필드로 사용.
// 채널이 생성된 시간을 함수가 호출된 시점의 타임스탬프로 저장.
export const createChannel = async ({title, description}) => {
const newChannelRef = DB.collection('channels').doc();
const id = newChannelRef.id;
const newChannel = {
id,
title,
description,
createAt: Date.now(),
};
await newChannelRef.set(newChannel);
return id;
}
export const createMessage = async ({ channelID, message }) => {
return await DB.collection('channels')
.doc(channelID)
.collection('messages')
.doc(message._id)
.set({
...message,
createAt:Date.now(),
});
}; //Channel.js
import React, {useState, useEffect, useLayoutEffect, useContext} from "react";
import styled, {ThemeContext} from "styled-components";
import {Text, FlatList } from 'react-native';
import {DB, createMessage, getCurrentUser} from "../utils/firebase";
import Input from '../components/Input';
import {Alert} from "react-native";
import {GiftedChat, Send} from 'react-native-gifted-chat';
import { MaterialIcons} from "@expo/vector-icons";
const Container = styled.View`
flex:1;
background-color: ${({ theme }) => theme.background};
`;
const SendButton = props => {
const theme = useContext(ThemeContext);
return (
<Send
{...props}
disabled={!props.text}
containerStyle={{
width:44,
height:44,
alignItems: 'center',
justifyContent: 'center',
marginHorizontal: 4,
}}
>
<MaterialIcons name='send'
size={24}
color={
props.text ? theme.sendButtonActive : theme.sendButtonInActive
}
/>
</Send>
);
};
const Channel = ({navigation, route }) => {
const theme = useContext(ThemeContext);
const {uid, name, photoURL} = getCurrentUser();
console.log(photoURL);
console.log(getCurrentUser());
const [messages, setMessages] = useState([]);
useEffect(() => {
const unsubscribe = DB.collection('channels')
.doc(route.params.id)
.collection('messages')
.orderBy('createAt', 'desc')
.onSnapshot(snapshot => {
const list = [];
snapshot.forEach(doc => {
list.push(doc.data());
});
setMessages(list);
});
return () => unsubscribe();
}, []);
const _handleMessageSend = async messageList => {
const newMessage = messageList[0];
try{
await createMessage({ channelID: route.params.id, message:newMessage});
} catch (e) {
Alert.alert('Send Message Error', e.message);
}
};
useLayoutEffect(() => {
navigation.setOptions({headerTitle: route.params.title || 'Channel'});
}, []);
return (
<Container>
<GiftedChat
listViewProps={{
style: {backgroundColor: theme.background},
}}
placeholder="Enter a message..."
messages={messages}
user={{ _id : uid, name, avatar: photoURL}}
onSend={_handleMessageSend}
alwaysShowSend={true}
textInputProps={{
autoCapitalize: 'none',
autoCorrect: false,
textContentType: 'none',
underlineColorAndorid: 'transparent',
}}
multiline={false}
renderUsernameOnMessage={true}
scrollToBottom={true}
renderSend={props => <SendButton {...props} /> }
/>
</Container>
);
};
export default Channel; |
Beta Was this translation helpful? Give feedback.
Answered by
Alchemist85K
May 2, 2022
Replies: 1 comment
-
안녕하세요 @cocoburger 님, 오타가 있네요. createAt 가 아니라 createdAt 으로 해야 합니다. 즐거운 하루 되세요 |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
cocoburger
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
안녕하세요 @cocoburger 님,
오타가 있네요. createAt 가 아니라 createdAt 으로 해야 합니다.
GiftedChat 레포를 참고하시기 바랍니다.
Gifted Chat
즐거운 하루 되세요
감사힙니다.