isimisi / sse.ts

sse.js written in typescript and using the fetch api

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

sse.ts

this project was inspired by sse.js

installation

yarn add @isimisi/sse.ts

usage in react

export default function MyComponent() {
    const [source, setSource] = useState<Source | null>(null)
    const [message, setMessage] = useState<string>("")

    useEffect(() => {
        const src = Source.get('http://localhost:3333/sse')

        setSource(src);

        return () => {
            src.close()
        }
    }, [])

    useEffect(() => {
        if (source) {
            source.on('message', e => {
                setMessage(e.data.message);
            })
        }

        return () => {
            if (source) {
                source.off('message')
            }
        }
    }, [source])

    return <div>{message}</div>
};

API reference

Type Method returns args
static Source.get Source url: string | URL config
static Source.post Source url: string | URL body: object config
public source.on void event: string listener: (e: SourceEvent) => void
public source.off void event: string
public source.close void
Type Interface
Config {
headers?: Record<string, string | number | boolean>,
withCredentials?: boolean
}
SourceEvent extends CustomEvent
{
data: any,
id?: string,
source?: Source,
readyState?: number
}

About

sse.js written in typescript and using the fetch api

License:MIT License


Languages

Language:TypeScript 100.0%