Ad

Redux How To Open A New Window After Ajax Complete

- 1 answer

Here is my problem:

I have a save button on a form. When the save button is clicked, it should sent the form data via ajax. When the ajax call succeeded, a new window should be opened.

The issue I run into is this (I am using React + Redux):

//inside the component class
handleSubmit = (e) => {
    this.props.dispatch( // calls ajax )
}


//inside the ajax action
dispatch => {
    fetch(...).then(response => {
        if (res.status >= 200 && res.status < 300) {
            window.open(...)
        }
    })
}

The problem with putting window.open() inside ajax calls is that the new window will be considered as pop-ups which are blocked by chrome and FF.

I think I should put window.open() inside handleSubmit to prevent browsers from blocking it. But how can I determine if dispatch has completed successfully inside handleSubmit? or is there any other places that I can call window.open() without being blocked?

Ad

Answer

Dispatch another action which triggers the window.open as soon as a promise hits .then() the AJAX request has finished as the promise is now resolved.

function openWindow(someData) {
    const url = someData.url;
    window.open(url);
    return { type: 'SOME_ACTION_TO_TAKE' };
}

export function someAction() {
  let endpoint = 'http://localhost:8000/myEndpoint/';
  return dispatch => {
    return Axios.post(endpoint)
      .then(response => response.data)
      .then(json => dispatch(openWindow(json)))
      .catch((err) => { //Do whatever to error here }); 
  };
}
Ad
source: stackoverflow.com
Ad