2 years ago

#39672

test-img

user3047450

Persisting React Context State to IndexedDB

I am currently transitioning from persisting my React Context State from localStorage to IndexedDB. The reason being I've hit the 10MB limit already and thus ran out of space.

Currently persisting the state to localStorage was fairly easy:

import React, { useEffect, createContext, useReducer} from 'react'
import { rootReducer } from './reducers/rootReducer'

export const initialState = {
  currentUser: {
    uuid: undefined,
    userName: undefined,
    authenticated: false,
  },
  users: [],
}

export default function Store({ children }) {
  
let appstate = JSON.parse(localStorage.getItem('appstate'))

const [state, dispatch] = useReducer(
   rootReducer,
   appstate || initialState
)

  useEffect(() => {
  localStorage.setItem('appstate', JSON.stringify(state));
  }, [state])

  return (
    <Context.Provider value={[state, dispatch]}>{children}</Context.Provider>
  )
}

export const Context = createContext(initialState)

This worked fine, and on every state change, the localStorage would rehydrate. It served well, until now when localStorage is full and thus need to migrate to IndexedDB.

As I only use a key-value pair, I use the lightweight async IndexedDB implementation 'idb-keyval', like so:

import React, { useEffect, createContext, useReducer, useRef} from 'react'
import { rootReducer } from './reducers/rootReducer'
import {set, get} from "idb-keyval"

export const initialState = {
  currentUser: {
    uuid: undefined,
    userName: undefined,
    authenticated: false,
  },
  users: [],
}

export default function Store({ children }) {
  
let appstate = useRef(null)
get('appstate').then( (value) => { appstate.current = value })

const [state, dispatch] = useReducer(
   rootReducer,
   appstate.current || initialState
)

  useEffect(() => {
  set('appstate', state)
  }, [state])

  return (
    <Context.Provider value={[state, dispatch]}>{children}</Context.Provider>
  )
}

export const Context = createContext(initialState)

Yet the state does not seem to be persisted in this case, as the appstate value is lost.

Thanks in advance.

reactjs

persistence

indexeddb

react-state

use-context

0 Answers

Your Answer

Accepted video resources