最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Migrate a API request from using promises to observable (using axios) - Stack Overflow

programmeradmin1浏览0评论

Lately, I have been trying to pull up API requests using rxjs in a react app and this is the solution that I came up with.

What about your thoughts on this?

Are there any good practices which I should follow up?

If there any good solutions please let me know.

import axios from 'axios';
import { Observable } from 'rxjs';

import './App.css';

export class App extends Component {
  state = {
    users: []
  };
  ponentDidMount() {
    const fetchUserSubscription$ = this.fetchUsersObservables();

    fetchUserSubscription$.subscribe(data =>
      this.setState({
        users: data
      })
    );
  }

  fetchUsers = async () => {
    const response = await axios.get(
      ''
    );
    const data = response.data;
    this.setState({ users: data });
  };

  fetchUsersObservables = () =>
    new Observable(observer => {
      axios
        .get('')
        .then(res => {
          observer.next(res.data);
          observerplete();
        })
        .catch(err => observer.error(err));
    });

  render() {
    const { users } = this.state;
    return (
      <div className="App">
        {users.map(u => (
          <ul key={u.id}>
            <li>{u.name}</li>
          </ul>
        ))}
      </div>
    );
  }
}

export default App;

Lately, I have been trying to pull up API requests using rxjs in a react app and this is the solution that I came up with.

What about your thoughts on this?

Are there any good practices which I should follow up?

If there any good solutions please let me know.

import axios from 'axios';
import { Observable } from 'rxjs';

import './App.css';

export class App extends Component {
  state = {
    users: []
  };
  ponentDidMount() {
    const fetchUserSubscription$ = this.fetchUsersObservables();

    fetchUserSubscription$.subscribe(data =>
      this.setState({
        users: data
      })
    );
  }

  fetchUsers = async () => {
    const response = await axios.get(
      'https://jsonplaceholder.typicode./users'
    );
    const data = response.data;
    this.setState({ users: data });
  };

  fetchUsersObservables = () =>
    new Observable(observer => {
      axios
        .get('https://jsonplaceholder.typicode./users')
        .then(res => {
          observer.next(res.data);
          observer.plete();
        })
        .catch(err => observer.error(err));
    });

  render() {
    const { users } = this.state;
    return (
      <div className="App">
        {users.map(u => (
          <ul key={u.id}>
            <li>{u.name}</li>
          </ul>
        ))}
      </div>
    );
  }
}

export default App;

Share Improve this question asked Mar 1, 2020 at 2:53 Inamul HassanInamul Hassan 1481 gold badge2 silver badges11 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

You don't have to convert your promises manually to observables. For rxjs > 6.0 you can use the from conversion function from the library (note for rxjs < 6.0 there is the fromPromise function).

Read about from here in the documentation.

Creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.

import { from } from 'rxjs';
const promise = axios.get('https://jsonplaceholder.typicode./users')
const observable = from(promise);

Advantage is that you don't have to write any custom observer, handling the success response, error responses and cancel request are all defined correctly for you.

发布评论

评论列表(0)

  1. 暂无评论