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
1 Answer
Reset to default 9You 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.