skip to Main Content

I was attempting to store the data from react-query in local storage so that it persists when the page is reloaded. However, I encountered an error stating that the JSON format is invalid.

    const [username, setUsername] = useState('')
    const [password, setPassword] = useState('')

    const navigate = useNavigate()

    const key = ['auth']

    const user = {
        user: username,
        password: password,
    }

    const { isLoading, data, isError, isFetching, refetch } = useQuery<ISessionContext | any>(key, async () => {
        const response = await axios.post(`http://localhost:3001/api/auth/login`, user)
        return response.data;
    }, {
        enabled: false,
        onSuccess: (data) => {
            setSessionInfos(data)
            localStorage.setItem('sessionData', JSON.stringify(data))
            if (data.isAuth) {
                navigate('/')
            }
        },
        onError: (error: any) => {
            if (error.response?.status === 401) {
                console.log('Não autorizado');
            }
        },
        staleTime: 8 * 60 * 60 * 1000,
    })

    function handleLogin() {
        refetch()
        setUsername('')
        setPassword('')
    }

And this in my context

import { PropsChildren } from '../types/GenericTypes'
import { ISessionContext } from '../types/interfaces/ISessionContext'
import { INITIAL_SESSION_STATE } from "./INITIAL_STATE";

export const AuthContext = createContext<any>(null);

export const AuthProvider = ({ children }: PropsChildren) => {
    const [sessionInfos, setSessionInfos] = useState<ISessionContext | null>(INITIAL_SESSION_STATE)

    useEffect(() => {
        const cachedData = localStorage.getItem('sessionData')
        if (cachedData) {
            console.log(cachedData)
            setSessionInfos(JSON.parse(cachedData))
        } else {
            setSessionInfos(INITIAL_SESSION_STATE)
        }

    }, [sessionInfos])

    const sessionContextValue: ISessionContext = {
        userLogged: sessionInfos?.userLogged || { name: '', user: '' },
        isAuth: sessionInfos?.isAuth || false,
    }

    return (
        <AuthContext.Provider value={{ sessionContextValue, setSessionInfos }}>{children}</AuthContext.Provider>
    )
}

These two errors are occurring

caught SyntaxError: "[object Object]" is not valid JSON
    at JSON.parse (<anonymous>)
    at index.tsx:15:34
    at invokePassiveEffectCreate (react-dom.development.js:23487:20)
    at HTMLUnknownElement.callCallback2 (react-dom.development.js:3945:14)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:16)
    at invokeGuardedCallback (react-dom.development.js:4056:31)
    at flushPassiveEffectsImpl (react-dom.development.js:23574:9)
    at unstable_runWithPriority (scheduler.development.js:468:12)
    at runWithPriority$1 (react-dom.development.js:11276:10)
    at flushPassiveEffects (react-dom.development.js:23447:14)
react-dom.development.js:20085 
---------------------------------------------------------------------------------
The above error occurred in the <AuthProvider> component:

    at AuthProvider (http://localhost:3000/src/contexts/index.tsx:21:3)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js:20085
scheduler.development.js:171 
----------------------------------------------------------------------------------
Uncaught SyntaxError: "[object Object]" is not valid JSON
    at JSON.parse (<anonymous>)
    at index.tsx:15:34
    at invokePassiveEffectCreate (react-dom.development.js:23487:20)
    at HTMLUnknownElement.callCallback2 (react-dom.development.js:3945:14)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:16)
    at invokeGuardedCallback (react-dom.development.js:4056:31)
    at flushPassiveEffectsImpl (react-dom.development.js:23574:9)
    at unstable_runWithPriority (scheduler.development.js:468:12)
    at runWithPriority$1 (react-dom.development.js:11276:10)
    at flushPassiveEffects (react-dom.development.js:23447:14)

I tried to verify if the data was being retrieved correctly from the API, and it seems that everything is working fine. I would like to find a way to store this data persistently, so that users do not have to log in again when the page is refreshed.

2

Answers


  1. Maybe ‘cachedData’ already has JSON data. Because the error itself indicates invalid JSON data. so there is no need to do JSON.parse.

    Login or Signup to reply.
  2. I think iChelsi might be right. The persisted data in the localstorage is already a json string. You most likely need to use JSON.parse() instead of stringify. As stringify is used to to convert a javascript object to a json string. the parse function however reads a json string and constructs an object for you (so the other way around.
    So on saving to localstorage you want to use stringify, when retrieving the data from localstorage you should be able to use the parse() function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search