reactjslocalforage

localForage in react app: self is undefined


I'm trying to use localForage in a reactjs app. Calling setItem and then getItem works exactly once. The value that was set with setItem is correctly recovered by getItem. If they are called again after that, a TypeError is thrown:

TypeError: self is undefined localforage.js:1012

The error can be reproduced with a minimal reactjs app, here's just a single functional component.
When the component is rendered, it calls setItem and getItem. It rerenders on a button click and calls setItem and getItem again. This causes the TypeError.

import React, { useState } from "react";
import { getItem, setItem } from "localforage";

function App() {
  const [state, setState] = useState(0);
  setItem("test", state).then(() => {
    console.log("used localForage");
  });

  getItem("test").then((val) => {
    console.log("got: ", val);
  });
  return (
    <button
      onClick={() => {
        setState(Math.floor(Math.random() * 10));
      }}
    >
      {state}
    </button>
  );
}

export default App;

Here is an online version on codesandbox.


Solution

  • Somehow it loses the context internally when importing methods separately, works fine when importing localforage as a whole

    import React, { useState } from "react";
    import localforage from "localforage";
    
    function App() {
      const [state, setState] = useState(0);
      localforage.setItem("test", state).then(() => {
        console.log("used localForage");
      });
    
      localforage.getItem("test").then(val => {
        console.log("got: ", val);
      });
      return (
        <button
          onClick={() => {
            setState(Math.floor(Math.random() * 10));
          }}
        >
          {state}
        </button>
      );
    }
    
    export default App;