Daniel
Daniel

Reputation: 6481

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

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.

Upvotes: 5

Views: 4094

Answers (1)

ivarni
ivarni

Reputation: 17878

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);

Upvotes: 4

Related Questions