Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux: Open external url after success response from an API

I want to open a url after receiving a success response from the api with the generated url. I'm trying to open that url inside the reducer like this:

window.open(url, '_blank');

this seems to be working fine for most of the browsers, but is not compatible in safari.

Any idea how can this be implemented to be cross browser compatible? Is there a way to do that with react-router-redux?

Thanks!

Update: I need to open an external url, not a route in the project so probably react-router is not the solution

like image 769
parecementeria Avatar asked Jul 01 '16 10:07

parecementeria


1 Answers

According to official redux docs, in reducers you shouldn't:

  • Mutate its arguments;
  • Perform side effects like API calls and routing transitions;
  • Call non-pure functions, e.g. Date.now() or Math.random().

If you are using redux-thunk middleware to make api requests, it would be better to perform redirects there.

For example:

// actions.js

function asyncApiCall() {
  return function (dispatch) {
    return fetch('/api')
      .then(response => response.json().then(body => ({ response, body })))
      .then(({ response, body }) => {
        if (response.ok) {
          window.open(url, '_blank');
        }
      });
  };
}
like image 178
1ven Avatar answered Nov 15 '22 05:11

1ven