Alok Prakash
Alok Prakash

Reputation: 331

Using Redux default store from window in React app

I have an React Web App that collects user saved information from local storage. First I retrieve saved information to window.store. I can see in console that window.store is there. But it always gives undefined error. I tried to make sleep so that after sleep, store can get data from global window object.

init.js

const InitializeApp = () => {
    let [getState, setState] = useState(false)
    useEffect(()=>{
        const asyncState = async() => {
            let store = await loadFromStorage()
            window.store = store
            await sleep(5000)
            console.log(store);
            setState(true)
        }
        asyncState()
    },[])
    if(!getState){
        return(
            <InitTemplate />
        )
    }else{
        return(
            <Main />
        )
    }
}

App.js

const Main = () => {
  return(
    <Provider store={Store}>
      <App />
    </Provider>
  );
}

store.js

const AppReducer = (state = window.store , action) => {
    switch(action.type){
        default :
            return state;
    }
}

Problem is I am getting undefined whenever I use useSelector(). How can I achieve this ?

Upvotes: 1

Views: 1303

Answers (1)

wowandy
wowandy

Reputation: 1312

Apparently you are trying to save the state to the localStorage and load it after reloading the page

I think that you do not need to create a Promise at the moment when you load the state from the localeStorage

Try to initialize the store as shown below

store.js

import {createStore} from "redux";
import AppReducer from "./AppReducer";

export const loadState = () => {
    try {
        const state = localStorage.getItem('state');
        if (state === null) {
            return undefined;
        }
        return JSON.parse(state);
    } catch (err) {
        return undefined;
    }
};

export const saveState = (state) => {
    try {
        const st = JSON.stringify(state);
        localStorage.setItem('state', st);
    } catch (err) {

    }
};

const throttle = (func, limit) => {
    let lastFunc;
    let lastRan;
    return function() {
        const context = this;
        const args = arguments;
        if (!lastRan) {
            func.apply(context, args);
            lastRan = Date.now();
        } else {
            clearTimeout(lastFunc);
            lastFunc = setTimeout(function() {
                if ((Date.now() - lastRan) >= limit) {
                    func.apply(context, args);
                    lastRan = Date.now()
                }
            }, limit - (Date.now() - lastRan))
        }
    }
};

const store = createStore(AppReducer, loadState());

store.subscribe(throttle(() => {
    // This callback is called on every state change.
    // Here your current state is written to the localStorage
    saveState(store.getState()); 
}, 2000));

export default store;

Upvotes: 1

Related Questions