reactjs - Hur man lagrar data som kommer från react-query i lokal lagring
Jag försökte lagra datan från react-query i lokal lagring så att den bevaras när sidan laddas om. Däremot stötte jag på ett fel som angav att JSON-formatet är ogiltigt.
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('')
}
Och detta i mitt sammanhang
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>
)
}
Dessa två fel uppstår
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)
Jag försökte verifiera om datan hämtades korrekt från API:et, och det verkar som att allt fungerar som det ska. Jag skulle vilja hitta ett sätt att lagra denna data permanent, så att användare inte behöver logga in igen när sidan uppdateras.
Svar #1
React Query erbjuder ett persistensplugin, som du kan använda för att bevara data i localstorage:
https://tanstack.com/query/v4/docs/react/plugins/persistQueryClient
Svar #2
Kanske har 'cachedData' redan JSON-data. Eftersom felet i sig indikerar ogiltig JSON-data, finns det alltså inget behov av att göra JSON.parse.