@codora/react-topic
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

CodoraDev - React Topic

A react hook to publish and subscribe to a topic from any component.

version npm downloads

Report Bug - Request Feature

Install

npm install --save @codora/react-topic

👉 Import

import {Topic, useTopic} from "@codora/react-topic";

🚀 Demo

Coming Soon...

🔬 Use Topic

Add the <Topic> context any where in your app. Add it near the root if you want to use topics for your whole app.

import {Topic} from "@codora/react-topic";

const App = () => {
  return (
    <Topic>
      //...
    </Topic>
  )
}

You will then have access to useTopic. It takes one argument, which will be the topic name, and one type argument, which will be the topic type.

useTopic will return two functions: publish and subscribe

import {useTopic} from "@codora/react-topic";

type User = {
    name
}
const SomeComponent = () => {
    const {publish, subscribe} =useTopic<User>("user")

    //...

publish is quite simple. All you need to do is pass in the data. This will add the data to its topic collection and send out an event to any subscribers.

//...

const newUser: User = buildUser();

<button onclick={()=> 
    publish(newUser) 
}>
    Add User
</button>

//...

subscribe will have to be used with in a useEffect for it to stay open and subscribed. subscribe will return an unSubscribe function which should be called when ever you do not need the subscription, else there will be a memory leak in your application.

The first argument is an onSubscribe function which is the callback function that will be called on an event. onSubscribe as two input arguments. The first is the topic updated collection array. We pass whole topic array with each event as it feels the most natural when making web applications. The second input argument is the event that was sent. In this event will hold the individual topic.

//...

  const [users, setUsers] = useState<User[]>([])
  const [event, setEvent] = useState<Event<User>>()

  useEffect(() => {
    const unSubscribe = subscribe((users, event) => {
      setUsers(users)
      setEvent(event)
    })
    return () => {
      unSubscribe()
    }
  }, []) 

//...

A full example is available here.

🦄 Upcoming Features

@codoradev/react-topic has all the potentials to grow further. Here are some of the upcoming features planned(not in any order),

  • On the first subscribe you can choose which which event to replay from

🛡️ License

This project is licensed under the MIT License - see the LICENSE file for details.

Readme

Keywords

Package Sidebar

Install

npm i @codora/react-topic

Weekly Downloads

1

Version

1.0.1

License

MIT

Unpacked Size

40.4 kB

Total Files

12

Last publish

Collaborators

  • jarrydmartin