diff --git a/src/app.tsx b/src/app.tsx index 928c74b..7e7a816 100644 --- a/src/app.tsx +++ b/src/app.tsx @@ -39,35 +39,49 @@ const newChatStore = ( const STORAGE_NAME = "chatgpt-api-web"; const STORAGE_NAME_SELECTED = `${STORAGE_NAME}-selected`; +const STORAGE_NAME_INDEXES = `${STORAGE_NAME}-indexes`; export function App() { - // init all chat store - const initAllChatStore: ChatStore[] = JSON.parse( - localStorage.getItem(STORAGE_NAME) || "[]" + // init indexes + const initAllChatStoreIndexes: number[] = JSON.parse( + localStorage.getItem(STORAGE_NAME_INDEXES) ?? "[0]" ); - if (initAllChatStore.length === 0) { - initAllChatStore.push(newChatStore()); - localStorage.setItem(STORAGE_NAME, JSON.stringify(initAllChatStore)); - } - const [allChatStore, setAllChatStore] = useState(initAllChatStore); + const [allChatStoreIndexes, setAllChatStoreIndexes] = useState( + initAllChatStoreIndexes + ); + useEffect(() => { + if (allChatStoreIndexes.length === 0) allChatStoreIndexes.push(0); + console.log("saved all chat store indexes", allChatStoreIndexes); + localStorage.setItem( + STORAGE_NAME_INDEXES, + JSON.stringify(allChatStoreIndexes) + ); + }, [allChatStoreIndexes]); + // init selected index const [selectedChatIndex, setSelectedChatIndex] = useState( parseInt(localStorage.getItem(STORAGE_NAME_SELECTED) ?? "0") ); useEffect(() => { + console.log("set selected chat index", selectedChatIndex); localStorage.setItem(STORAGE_NAME_SELECTED, `${selectedChatIndex}`); }, [selectedChatIndex]); - const chatStore = allChatStore[selectedChatIndex]; - const setChatStore = (cs: ChatStore) => { - allChatStore[selectedChatIndex] = cs; - setAllChatStore([...allChatStore]); + const getChatStoreByIndex = (index: number): ChatStore => { + const key = `${STORAGE_NAME}-${index}`; + const val = localStorage.getItem(key); + if (val === null) return newChatStore(); + return JSON.parse(val) as ChatStore; }; - useEffect(() => { - console.log("saved", allChatStore); - localStorage.setItem(STORAGE_NAME, JSON.stringify(allChatStore)); - }, [allChatStore]); + const chatStore = getChatStoreByIndex(selectedChatIndex); + const setChatStore = (cs: ChatStore) => { + console.log("saved chat", selectedChatIndex, chatStore); + localStorage.setItem( + `${STORAGE_NAME}-${selectedChatIndex}`, + JSON.stringify(chatStore) + ); + }; return (