Last active
November 10, 2017 19:51
-
-
Save andrIvash/0597313f19dc8bc5ed3c3bce85c10574 to your computer and use it in GitHub Desktop.
pagination
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class getApiDataList { | |
| constructor (url, indexProp, sizeProp, options = {}) { | |
| this.options = options; | |
| this.indexProp = indexProp; | |
| this.sizeProp = sizeProp; | |
| this.mainUrl = new URL(url); | |
| this.params = new URLSearchParams(this.mainUrl.search); | |
| this._index = +this.params.get(this.indexProp); | |
| } | |
| get size () {return +this.params.get(this.sizeProp)}; | |
| get index () {return this._index}; | |
| set index (value) {this._index = value}; | |
| get url() { | |
| this.params.set(this.indexProp, this.index); | |
| this.params.set(this.sizeProp, this.size); | |
| return `${this.mainUrl.origin}${this.mainUrl.pathname}?${this.params}`; | |
| } | |
| *getRemoteData() { | |
| yield fetch(this.url, this.options).then((response) => { | |
| if (response.ok) { | |
| this.index ++; | |
| return response.json() | |
| } | |
| throw new Error('Network response was not ok.'); | |
| }); | |
| } | |
| getNext(generator = this.getRemoteData(), yieldValue) { | |
| let next = generator.next(yieldValue); | |
| if (!next.done) { | |
| return next.value.then( | |
| result => {return result}, | |
| err => generator.throw(err) | |
| ).catch( err => console.warn('---err ', err)); | |
| } | |
| } | |
| } | |
| let fr2 = new getApiDataList( | |
| 'https://api.github.com/users/userName/repos?page=1&per_page=20', // main api url | |
| 'page', // index key name | |
| 'per_page', // size per page key name | |
| // fetch options | |
| { | |
| method: 'GET', | |
| headers: new Headers({ | |
| "Accept": "application/vnd.github.mercy-preview+json" | |
| }) | |
| } | |
| ); | |
| //add btn and event listener on it | |
| const btn = document.querySelector('#btn'); | |
| btn.addEventListener('click', () => { | |
| fr2.getNext().then(res => { | |
| if(res.length) { | |
| console.log('---result ', res); //success | |
| } else { | |
| console.log('---- end') // no data | |
| } | |
| }); | |
| }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment