reactjstypescriptoboe.js

Rewrite fetch call to oboe for json streams with Typescript


I have this fetch call:

 api<T>(url: string, headers: Request): Promise<T> {
        return fetch(url, headers)
            .then(response => {
                if (!response.ok) {
                    throw new Error(response.statusText);
                }
                return response.json().then(data => data as T);
            })
            .catch((error: Error) => {
                throw error;
            });
    }
    componentDidMount(){
        this.api<Array<Response>>(url, requestData)
            .then(data  => {
                this.setState({
                    jobs: data
                });
            })
            .catch(error => {
                console.error(error);
            });
    }

But the response that I get is a stream+json so I get invalid json at .json().

I saw that there is a library that can help me: http://oboejs.com/examples

But I'm having issues using oboe and typescript (beginner) (using https://www.npmjs.com/package/@types/oboe).

I tried:

api<T>(headers: Request): Oboe<T> {
        return oboe(headers)
            .done(function(response) {
                return response;
            })
            .fail(function(error: Error) {
                throw error;
            });
    }
    componentDidMount(){
        this.api<Array<Response>>(requestData)
            .done(data  => {
                this.setState({
                    jobs: data
                });
            })
            .fail(error => {
                console.error(error);
            });
    }

But there are obvious errors as I don't know what type oboe should return so I get an error Oboe is not generic.


Solution

  • Replacing the callback logic with a Promise

    api<T>(headers: Request): Promise<T> {
      return new Promise((resolve, reject) => {
        oboe(headers)
          .done(data => resolve(data))
          .fail(err => reject(err));
      });
    }
    

    Calling it (the way you did with Promise/fetch)

    componentDidMount(){
        this.api<Array<Response>>(url, requestData)
            .then(data  => {
                this.setState({
                    jobs: data
                });
            })
            .catch(error => {
                console.error(error);
            });
    }