#What's the best way to store data locally?

26 messages ยท Page 1 of 1 (latest)

plucky skiff
#

I'm building a "Reminder App" where a user can add, edit, and remove reminders. In brief, you set up your reminders and intervals, and it rings when you should be reminded.

I'm going to do auth for user data, and postgres for the reminders, intervals, etc., but i want the chat history to be saved locally. No need for this to be saved on the database.

What's the best way to save this type on data using Next.js 14?

delicate tendonBOT
#

๐Ÿ”Ž This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

๐Ÿ•ต๏ธ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

โœ… You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

onyx ember
#

local storage.

#

Only real option

plucky skiff
#

Using the window.localStorage API?

onyx ember
#

If you dont wanna store the data yourself.

#

Yep

plucky skiff
#

kk, I was playing around and creating a hook for this.

#
import { useState } from "react"

function useLocalStorage<T>(key: string, initialValue: T) {
    const [storedValue, setStoredValue] = useState<T>(() => {
        if (typeof window === "undefined") {
            return initialValue
        }
        try {
            const item = window.localStorage.getItem(key)
            return item ? JSON.parse(item) : initialValue
        } catch (error) {
            console.log(error)
            return initialValue
        }
    })

    const setValue = (value: T | ((val: T) => T)) => {
        try {
            const valueToStore =
                value instanceof Function ? value(storedValue) : value
            setStoredValue(valueToStore)
            if (typeof window !== "undefined") {
                window.localStorage.setItem(key, JSON.stringify(valueToStore))
            }
        } catch (error) {
            console.log(error)
        }
    }

    return [storedValue, setValue] as const
}

export default useLocalStorage
#

I was wondering if there was better practice.

#

not sure if that works yet, haven't really tested well.

onyx ember
#

remember, a single site can only take up 5mb of local storage, so you have to have some logic in there to handle it

plucky skiff
#

I understand the limits.

#

but, I don't understand your recommended solution.

#

this is all just going to be text.

onyx ember
#

nvm the other comment.

plucky skiff
#

kk, i'll get there when i get there ๐Ÿ˜„

#

if i hit a limit, i'll just clear the first half of the history

onyx ember
#

Yeah, you can do things to 'compress' the data, if you wanted. To make the 5mb go further if that makes sense?

plucky skiff
#

ty for your answer ๐Ÿ™‚

onyx ember
#

Np ๐Ÿ™‚

delicate tendonBOT
#
โœ… Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer

[Click here](#1236836880138633277 message)

plucky skiff
#

in case if someone comes back or if you wanna see @onyx ember , this worked perfectly.

"use client"

import {
    type CommandHistory,
    TerminalHistory
} from "@/components/TerminalHistory"
import TerminalInput from "@/components/TerminalInput"
import TerminalPrompt from "@/components/TerminalPrompt"
import commands from "@/utilities/commands"
import { type ChangeEvent, type FormEvent, useEffect, useState } from "react"

export default function Terminal() {
    const [command, setCommand] = useState("")
    const [commandHistory, setCommandHistory] = useState<CommandHistory[]>([])

    useEffect(() => {
        const storedCommandHistory = localStorage.getItem("commandHistory")
        if (storedCommandHistory) {
            setCommandHistory(JSON.parse(storedCommandHistory))
        }
    }, [])

    const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
        setCommand(e.target.value)
    }

    const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        const trimmedCommand = command.trim().toLowerCase()
        const response = commands[trimmedCommand] || "Unknown command"
        const currentTimestamp = new Date()
        const id = currentTimestamp.getTime().toString()
        const updatedCommandHistory = [
            ...commandHistory,
            { id, timestamp: currentTimestamp, command: trimmedCommand, response }
        ]
        setCommandHistory(updatedCommandHistory)
        localStorage.setItem(
            "commandHistory",
            JSON.stringify(updatedCommandHistory)
        )
        setCommand("")
    }

    return (
        <main className="h-full border-2 rounded-md p-4 overflow-auto text-xs sm:text-sm md:text-base border-[#98971a] bg-[#282828] text-[#ebdbb2]">
            <TerminalPrompt username="david" />
            <div className="flex flex-col">
                <TerminalHistory commandHistory={commandHistory} />
                <TerminalInput
                    command={command}
                    onInputChange={handleInputChange}
                    onSubmit={handleSubmit}
                />
            </div>
        </main>
    )
}
onyx ember
#

Perfect! Good idea ๐Ÿ™‚