From 46642e24c23e7aced217ee670b773b4e06e2e2e8 Mon Sep 17 00:00:00 2001 From: Jing Hua Date: Mon, 6 Mar 2023 00:35:18 +0800 Subject: [PATCH] restore old chats --- src/App.tsx | 47 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 29e0190..fd5ecb5 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -5,14 +5,55 @@ import Chat from './components/Chat'; import Menu from './components/Menu'; import useInitialiseNewChat from '@hooks/useInitialiseNewChat'; +import { ChatInterface } from '@type/chat'; +import { Theme } from '@type/theme'; function App() { const initialiseNewChat = useInitialiseNewChat(); + const setChats = useStore((state) => state.setChats); + const setTheme = useStore((state) => state.setTheme); + const setApiKey = useStore((state) => state.setApiKey); + const setCurrentChatIndex = useStore((state) => state.setCurrentChatIndex); useEffect(() => { - const chats = useStore.getState().chats; - if (!chats || chats.length === 0) { - initialiseNewChat(); + // legacy local storage + const oldChats = localStorage.getItem('chats'); + const apiKey = localStorage.getItem('apiKey'); + const theme = localStorage.getItem('theme'); + + if (apiKey) { + // legacy local storage + setApiKey(apiKey); + localStorage.removeItem('apiKey'); + } + + if (theme) { + // legacy local storage + setTheme(theme as Theme); + localStorage.removeItem('theme'); + } + + if (oldChats) { + // legacy local storage + try { + const chats: ChatInterface[] = JSON.parse(oldChats); + if (chats.length > 0) { + setChats(chats); + setCurrentChatIndex(0); + } else { + initialiseNewChat(); + } + } catch (e: unknown) { + console.log(e); + initialiseNewChat(); + } + localStorage.removeItem('chats'); + } else { + // existing local storage + const chats = useStore.getState().chats; + if (!chats || chats.length === 0) { + initialiseNewChat(); + } } }, []);