Search code examples
reactjsreduxstore

Tell store to update without an actual data change


I am trying to cleanup my React/Redux application's bootstrapping.

I create my redux story like this:

store = createStore(reducer, { ...initialState });

And on the next line I subscribe:

store.subscribe(() => ReactDOM.render(
  <App foo={store.getState().foo} />,
  document.getElementById('root')
));

When I start my application, the rendering of the App control is not occurring. I suppose this is because my subscribe is not firing since no data has changed yet.

I understand I could move the subscribe callback to a separate function and invoke it manually, but I was hoping to not have to create the separate function.

Is there a clean way to tell my store object to go ahead and fire it's subscribe callback without making an explicit data change?


Solution

  • Yes, and no.

    Store subscribers are called at the end of every call to dispatch(), regardless of whether the state was actually changed by the root reducer function. So, you could in theory do dispatch({type : "DUMMY_ACTION_NO_REDUCER_CARES_ABOUT"}), and that will trigger the subscribers.

    However, that's really pointless. It's much simpler to do:

    const renderApp =  () => {
        ReactDOM.render(
            <App foo={store.getState().foo} />,
             document.getElementById('root')
        );
    };
    
    store.subscribe(renderApp);
    renderApp();
    

    Beyond that, unless you're just experimenting around with the bare basics of React and Redux and trying to learn how they work, you shouldn't actually be subscribing to the store manually. Instead, you should use the official React-Redux library, which provides a connect() function that abstracts away the process of subscribing to the store for you.