简体   繁体   中英

Migrate a API request from using promises to observable (using axios)

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: []
  };
  componentDidMount() {
    const fetchUserSubscription$ = this.fetchUsersObservables();

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

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

  fetchUsersObservables = () =>
    new Observable(observer => {
      axios
        .get('https://jsonplaceholder.typicode.com/users')
        .then(res => {
          observer.next(res.data);
          observer.complete();
        })
        .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;

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.com/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM