'Where to store Request promise before Abort in React project?

I want to cancel pending requests when the connection turns offline. To do that, I store all of my requests in my window.myRequests array. After the connection turns offline, I iterate the window.myRequests array and call item.abort() [I'm using superagent as a client] It works great. But I don't think that storing requests in window object is correct.

Where to store this array in a React application? Is the redux the correct address?

I want to make it accessible from anywhere in the component tree. Because I'm handling online/offline status in a single place.

Thanks in advance.



Solution 1:[1]

I think it's doesn't matter if u store it at a variable in global scope(window) or in local scopre(e.g,object, class instance), even redux.Only the difference between them is your code habit.I suggest u put the vars may cause page to render in redux.For better maintenance, u can make a class to store it, for example:

class RequestQueue {
    _queue = [];
  
    store(req) {
      this._queue.push(req);
    }

    remove(req) {
        const index = this._queue.findIndex(r => r === req);
        if (index > -1) {
            this._queue.splice(index, 1);
        }
    }

    /**
     * other functions:
     * ...
     */
}

const cache = new RequestQueue();
cache.store(...);
cache.remove(...);

// abort
cache._queue.forEach(req => abort(req))

If there is no problem with the function: abort, u could get what u want.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eder