게시글
질문&답변
2022.11.09
optimistic UI 중 mutateChat 에서 Objects are not valid as a React child (found: Tue Nov 08 2022 17:24:47 GMT+0900 (한국 표준시)). If you meant to render a collection of children, use an array instead.
메시지 부분은 chat 을 말씀하시는걸까요? ㅠdata.createdAt을 주석처리했더니 에러가 바뀌긴 했어요 근데 에러가 어디서 나는지 알기가 어렵네요..import React, { memo, useMemo, VFC } from 'react'; import { ChatWrapper } from './styles'; import gravatar from 'gravatar'; import regexifyString from 'regexify-string'; import { Link, useParams } from 'react-router-dom'; interface Props { data: any; } // a?.b optional chaining // a??b nullish coalescing const Chat: VFC = ({ data }) => { const user = data.Sender; const { workspace } = useParams(); const result = useMemo( () => regexifyString({ input: data.content, pattern: /@\[(.+?)]\((\d+?)\)|\n/g, decorator(match, index) { const arr: string[] | null = match.match(/@\[(.+?)]\((\d+?)\)/)!; if (arr) { return ( @{arr[1]} ); } return ; }, }), [data.content], ); return ( (사진) {user.nickname} {/* {data.createdAt} */} {result} ); }; export default memo(Chat); (사진)import Chat from '@components/chat'; import { ChatZone, Section, StickyHeader } from '@components/chatList/styles'; import { IChat, IDM } from '@typings/db'; import React, { useCallback, forwardRef, ForwardedRef, RefObject, VFC } from 'react'; import { Scrollbars } from 'react-custom-scrollbars'; interface Props { chatSections: { [key: string]: IDM[] }; setSize: (f: (size: number) => number) => Promise; isReachingEnd: boolean; scrollRef: RefObject; } const ChatList: VFC = ({ chatSections, setSize, scrollRef, isReachingEnd }) => { const onScroll = useCallback( (values: any) => { if (values.scrollTop === 0 && !isReachingEnd) { console.log('가장 위'); setSize((prevSize) => prevSize + 1).then(() => { // 스크롤 위치 유지 if (scrollRef?.current) { scrollRef.current?.scrollTop(scrollRef.current?.getScrollHeight() - values.scrollHeight); } }); } }, [scrollRef, isReachingEnd, setSize], ); return ( {Object.entries(chatSections).map(([date, chats]) => { return ( {date} {chats.map((chat) => ( ))} ); })} ); }; export default ChatList; import ChatBox from '@components/chatBox'; import ChatList from '@components/chatList'; import useInput from '@hooks/useInput'; import useSocket from '@hooks/useSocket'; import { Container, DragOver, Header } from '@pages/directMessage/styles'; import { IDM } from '@typings/db'; import fetcher from '@utils/fetcher'; import makeSection from '@utils/makeSection'; import axios from 'axios'; import React, { useCallback, useEffect, useRef, useState } from 'react'; import gravatar from 'gravatar'; import Scrollbars from 'react-custom-scrollbars'; import { useParams } from 'react-router-dom'; import useSWR from 'swr'; import useSWRInfinite from 'swr/infinite'; import Workspace from '@layouts/workspace'; const DirectMessage = () => { const { workspace, id } = useParams(); console.log(id, 'id'); const { data: userData } = useSWR(`/api/workspaces/${workspace}/users/${id}`, fetcher); const { data: myData } = useSWR('/api/users', fetcher); const [chat, onChangeChat, setChat] = useInput(''); const { data: chatData, mutate: mutateChat, setSize, } = useSWRInfinite( (index) => `/api/workspaces/${workspace}/dms/${id}/chats?perPage=20&page=${index + 1}`, fetcher, ); const [socket] = useSocket(workspace); const isEmpty = chatData?.[0]?.length === 0; const isReachingEnd = isEmpty || (chatData && chatData[chatData.length - 1]?.length (null); const [dragOver, setDragOver] = useState(false); const onSubmitForm = useCallback( (e: any) => { e.preventDefault(); console.log(chat); if (chat?.trim() && chatData) { const savedChat = chat; mutateChat((prevChatData) => { prevChatData?.[0].unshift({ id: (chatData[0][0]?.id || 0) + 1, content: savedChat, SenderId: myData.id, Sender: myData, ReceiverId: userData.id, Receiver: userData, createdAt: new Date(), }); return prevChatData; }, false).then(() => { setChat(''); scrollbarRef.current?.scrollToBottom(); }); axios .post(`/api/workspaces/${workspace}/dms/${id}/chats`, { content: chat, }) .then(() => { mutateChat(); }) .catch(console.error); } }, [chat, chatData, myData, userData, workspace, id], ); const onMessage = useCallback((data: IDM) => { // id는 상대방 아이디 if (data.SenderId === Number(id) && myData.id !== Number(id)) { mutateChat((chatData) => { chatData?.[0].unshift(data); return chatData; }, false).then(() => { if (scrollbarRef.current) { if ( scrollbarRef.current.getScrollHeight() { scrollbarRef.current?.scrollToBottom(); }, 50); } } }); } }, []); useEffect(() => { socket?.on('dm', onMessage); return () => { socket?.off('dm', onMessage); }; }, [socket, onMessage]); // 로딩 시 스크롤바 제일 아래로 useEffect(() => { if (chatData?.length === 1) { setTimeout(() => { scrollbarRef.current?.scrollToBottom(); }, 100); } }, [chatData]); const onDrop = useCallback( (e: any) => { e.preventDefault(); console.log(e); const formData = new FormData(); if (e.dataTransfer.items) { // Use DataTransferItemList interface to access the file(s) for (let i = 0; i { setDragOver(false); mutateChat(); }); }, [mutateChat, workspace, id], ); const onDragOver = useCallback((e: any) => { e.preventDefault(); console.log(e); setDragOver(true); }, []); if (!userData || !myData) { return null; } const chatSections = makeSection(chatData ? chatData.flat().reverse() : []); return ( (사진) {userData.nickname} {dragOver && 업로드!} ); }; export default DirectMessage;
- 0
- 2
- 494
질문&답변
2022.10.27
채널 생성시 channelData.map is not a function
우선 then 안에서 res.data 잘 들어오는거 확인했고, mutate(res.data,false)로 swr이 전역관리하는거로 이해했는데const onCreateChannel = useCallback( (e) => { e.preventDefault(); axios .post( `/api/workspaces/${workspace}/channels`, { name: newChannel, }, { withCredentials: true }, ) .then((res) => { setShowCreateChannelModal(false); mutate(res.data, false); console.log(res.data, 'res.data'); setNewChannel(''); }) .catch((err) => { console.dir(err); toast.error(err.response?.data, { position: 'bottom-center' }); }); }, [newChannel], ); (사진)이렇게 찍어보면 (사진)배열이 풀리면서? 에러나는 것 같습니다..(사진)이런식으로 처리해줘야 하나 해봤는데 아닌것같고...고민 계속 해보겠습니다..
- 0
- 3
- 418
질문&답변
2022.10.19
로그인 -> workspace로 이동하지 않는 이슈
ㅇㅇlogin에서 onSubmit 안쪽과 바깥쪽에 ,fetcher에 콘솔을 추가하여 실행해봤습니다.import axios from 'axios'; const fetcher = (url: string) => { axios .get(url, { withCredentials: true, // withCredentials: true, proxy를 안써서 백엔드, 프론트 포트가 다르면 쿠키를 전달할 수 없음. 로그인이 됐는지 확인불가. 그래서 이거로 해결. }) .then((response) => console.log(response.data, '응답')); }; export default fetcher; import useInput from '@hooks/useInput'; import React, { useCallback, useState } from 'react'; import { Header, Button, Error, Form, Input, Label, LinkContainer, Success } from '@pages/signup/styles'; import { Link, Navigate } from 'react-router-dom'; import axios from 'axios'; import useSWR from 'swr'; import fetcher from '@utils/fetcher'; const LogIn = () => { const { data, error, mutate } = useSWR('/api/users', fetcher); const [logInError, setLogInError] = useState(false); const [email, onChangeEmail] = useInput(''); const [password, onChangePassword] = useInput(''); const onSubmit = useCallback( (e) => { e.preventDefault(); setLogInError(false); axios .post( '/api/users/login', { email, password }, { withCredentials: true, }, //get일때와 post일때 withCredentials 위치가 다르다. ) .then((response) => { console.log(response.data, 'onSubmit안에서'); mutate(response.data); }) .catch((error) => { setLogInError(error.response?.data?.statusCode === 401); }); }, [email, password], ); console.log(data, 'login컴포에서'); if (data) { return ; } return ( Sleact 이메일 주소 비밀번호 {logInError && 이메일과 비밀번호 조합이 일치하지 않습니다.} 로그인 아직 회원이 아니신가요? 회원가입 하러가기 ); }; export default LogIn; import fetcher from '@utils/fetcher'; import axios from 'axios'; import React, { FC, useCallback } from 'react'; import { Navigate } from 'react-router-dom'; import useSWR from 'swr'; const Workspace: FC = ({ children }) => { const { data, error, mutate } = useSWR('/api/users', fetcher); const onLogout = useCallback(() => { axios .post('/api/users/logout', null, { withCredentials: true, }) .then((res) => { mutate(res.data); }); }, []); if (!data) { return ; } return ( 로그아웃 {children} ); }; export default Workspace; (사진)(사진)새로고침 하면 fetcher가 작동되면서는 데이터가 찍히는데로그인 컴포넌트에서 useSWR의 data가 계속 초기화가 되는 것 같은데..계속 고민해보겠습니다.. ㅠ뭘까요.. 다른 댓글 보니까 조건을 data===false 로 해보라고 하신거 보고 해보니(사진)이런 타입에러가 뜨네요...ㅠㅠ
- 0
- 2
- 435
질문&답변
2022.10.12
proxy 504 에러
(사진)npm run dev로 열었고이렇게 열려있는게 켜진상태 맞지않나요?
- 0
- 2
- 696
질문&답변
2022.05.02
findOne(id) 에서 에러가 발생한 경우 해결법
findOneBy({id}) 같네요.. fineOne이 아니라..
- 22
- 6
- 3.1K