Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Redux - call dispatch without connect (not from a react component)

Tags:

I have a scheduled function which fetches data from the server every x minutes and i want it to update the state with the response:

api.fetchData().then(
    (response) => {
        dispatch(Actions.updateConfiguration(response));
    }
};

This function should not be a react component since it doesn't render anything.

However i can't seem to figure out how to inject dispatch function without using connect, which requires it to be a react component.

Thanks.

like image 882
Daniel Avatar asked Jul 19 '16 12:07

Daniel


1 Answers

We've a similar thing (A recurring check on wether the auth token is still valid) and we did the following.

In our little "util" function we receive the redux store as a parameter

export function startSessionTimer(store) {
    const intervalId = setInterval(() => {
        if ( ... ) {
            store.dispatch( ... );
            clearInterval(intervalId);
        }
    }, (15 * 60 * 1000));
}

Then, where we set up our app and create the store, we also kick-start the timer.

const store = configureStore( ... );
startSessionTimer(store);
like image 113
ivarni Avatar answered Oct 06 '22 00:10

ivarni