Anurag Jain
Anurag Jain

Reputation: 453

Redux possibibilty to dispatch an action on server side

I'm beginner with redux and create universal react redux application.

Is this any option to dispatch async action on server side like store.dispatch(actions.getOutput()) on server side.

getOutput is an asynchronous action which fetch some api on call and change the state on redux.

I Know to dispatch it on client side with redux-thunk middleware but not understanding the process on server side

let context = {},
    status = 200;

const allReducers = combineReducers({
    ...reducers
});

const store = createStore(
    allReducers,
    compose(
        applyMiddleware(thunkMiddleware, promise)
    )
);



    const preloadedStore = store.getState()
    store.dispatch(actions.getStories());
    const finalState = store.getState();


    const ctx = ReactDomServer.renderToString(
    <Provider store={store}>
        <StaticRouter context={context} location={req.url}>
            <App/>
        </StaticRouter>
    </Provider>
    ),
    reactHelmet = ReactHelmet.renderStatic();

    if(context.url){
        return res.redirect(302, context.url);
    }

    if(context.status === 404){
        status = 404;
    }

    let page = renderOutput(ctx, finalState, reactHelmet);
    res.status(status).send(page);

Upvotes: 2

Views: 3312

Answers (1)

Faris
Faris

Reputation: 544

From the docs of redux-thunk, if you define your action like this:

function makeASandwichWithSecretSauce(forPerson) {

  // Invert control!
  // Return a function that accepts `dispatch` so we can dispatch later.
  // Thunk middleware knows how to turn thunk async actions into actions.

  return function (dispatch) {
    return fetchSecretSauce().then(
      sauce => dispatch(makeASandwich(forPerson, sauce)),
      error => dispatch(apologize('The Sandwich Shop', forPerson, error))
    );
  };
}

you can then use it like this

store.dispatch(
  makeASandwichWithSecretSauce('My wife')
).then(() => {
  console.log('Done!');
});

Which means, on the server side you can do

store.dispatch(makeASandwichWithSecretSauce("My wife")).then(() => {

  const ctx = ReactDomServer.renderToString(
    <Provider store={store}>
      <StaticRouter context={context} location={req.url}>
        <App />
      </StaticRouter>
    </Provider>
  );

  const reactHelmet = ReactHelmet.renderStatic();

  const page = renderOutput(ctx, finalState, reactHelmet);

  res.status(status).send(page);
});

Upvotes: 3

Related Questions