# useStream

Source code is hosted on [GitHub](https://github.com/corets/use-stream)

{% tabs %}
{% tab title="yarn" %}

```bash
yarn add @corets/use-stream
```

{% endtab %}

{% tab title="npm" %}

```
npm install --save @corets/use-stream
```

{% endtab %}
{% endtabs %}

This library is built on top of these packages:

{% content-ref url="../observables/async" %}
[async](https://docs.corets.io/observables/async)
{% endcontent-ref %}

{% content-ref url="use-async" %}
[use-async](https://docs.corets.io/hooks/use-async)
{% endcontent-ref %}

## useStream() <a href="#usestream" id="usestream"></a>

Takes a function or an instance of [`Async`](https://docs.corets.io/observables/async) and turns it into a repeating stream of data:

```typescript
import React from "react"
import { createAsync } from "@corets/async"
import { useStream } from "@corets/use-stream"

const sharedQuery = createAsync(async () => "some global data")
    
const Example = () => {
  const stream = useStream(1000, async () => `Current date is ${new Date().toISOString()}`)
  const globalStream = useStream(5000, sharedQuery, ["some", "dependencies"])
  
  const handleReload = () => stream.run()
  const handleCancel = () => stream.cancel()
  
  if (stream.isRunning() && ! stream.getResult()) {
    return <h1>Loading for the first time</h1>
  }
  
  if (stream.isErrored()) {
    return <h1>There was an error :(</h1>
  }
  
  return (
    <div>
      Result: {stream.getResult()} 
      {stream.isRunning() && "Refreshing ..."}
      <button onClick={handleReload}>Reload</button>
      <button onClick={handleCancel}>Cancel</button>
    </div>
  )
}
```

{% hint style="info" %}
Check out [Async](https://docs.corets.io/observables/async) and [useAsync](https://docs.corets.io/hooks/use-async) documentation for more details.
{% endhint %}
