Search code examples
reactjsasync-awaites6-promiselocalforage

return a boolean value from localForage getItem


enter image description here

import localForage from 'localforage';
import React from 'react';
import globalHook, { Store } from 'use-global-hook';

interface State {
  isLoading: boolean;
  isAuthenticated: boolean;
}

type Action = {
  setIsLoading: (isLoading: boolean) => void;
  setIsAuthenticated: (isAuthenticated: boolean) => void;
};

const authenticate = localForage
  .getItem('token')
  .then((value) => {
    return value ? true : false;
  })
  .catch(function (err) {});

const initialState: State = {
  isLoading: false,
  isAuthenticated: false,
};

const actions = {
  setIsLoading: (store: Store<State, Action>, isLoading: boolean) => {
    store.setState({ ...store.state, isLoading });
  },
  setIsAuthenticated: (
    store: Store<State, Action>,
    isAuthenticated: boolean
  ) => {
    store.setState({ ...store.state, isAuthenticated });
  },
};

const useGlobal = globalHook<State, Action>(React, initialState, actions);

export default useGlobal;

Hi, I am implementing a login functionality in reactjs and using localforage for storing tokens. I have an isAuthenticated state in the global state. Now I wanted to change the isAuthenticated initialValue value to either true or false based on whether the localForage has the token or not. Thus I wanted to return a boolean value if the localForage has a value or not. But now it returns a promise rather than a boolean with localForage. Thanks in advance for any help


Solution

  • I think your authenticate function is a bit wrong. What I would do, I would make authenticate a function and then that function would call localForage to get the token that would be then returned.

    I've made a quick example that works using localForage. I set the token first when the component is rendered and then get it from the localForage. It then renders the value correctly and no need to do anything else. Please use this as an example. You can also find it here

    import React, { useState, useEffect } from "react";
    import localForage from "localforage";
    
    export default function App() {
      const [token, setToken] = useState("");
      const [error, setError] = useState(null);
    
      const authenticate = () => {
        return localForage
          .getItem("token")
          .then((value) => setToken(value))
          .catch((err) => setError(err));
      };
    
      useEffect(() => {
        localForage.setItem("token", "token123");
        authenticate();
      }, []);
    
      return (
        <div className="App">
          {error ? <p>Error {error}</p> : <p>Token: {token}</p>}
        </div>
      );
    }