Observables are not natively supported in React. However, there are several libraries that allow developers to integrate observables into their React applications. One of the most popular libraries for this purpose is RxJS. Here is an example of how to use observables in React with RxJS:
```
import React, { useEffect, useState } from ‘react’;
import { from } from ‘rxjs’;
function Example() { const [data, setData] = useState(null);
useEffect(() => { const observable = from(fetch(‘https://api.example.com’)); const subscription = observable.subscribe({ next(response) { setData(response.data); }, error(err) { console.error(‘Error: ‘ + err); }, complete() { console.log(‘Completed’); } }); // clean up on unmount return () => { subscription.unsubscribe(); }; }, []); // Empty array causes the effect to only run once on mount return (export default Example;
```
In the example above, we’re using the `useEffect` hook to set up our observable when the component mounts. We’re using the `from` function from `rxjs` to create an observable from a promise. The `fetch` call returns a promise that resolves to the response from the API.
We then subscribe to the observable inside the `useEffect` hook. The `next` function is called each time the observable emits a new value – in this case, when the promise returned by `fetch` resolves. We then set the state with the data received from the API by calling `setData`.
Finally, we return a clean-up function that calls `unsubscribe` on our subscription. This gets run when the component unmounts, effectively cancelling the observable if the API call has not yet completed by the time the component unmounts.
In the render part of the component, we show the data if it is available; otherwise, we show a loading message.
This is a basic example to illustrate how observables might be used in a React component with RxJS. A real-world application would likely involve more complex use cases.