use-emitter
React helper for event emitters and socket.io
Installation
npm install use-emitter
yarn add use-emitter
Usage
EmitterProvider
// App.jsximport React from 'react'; import EmitterProvider from 'use-emitter'; // import some kind of event emitterimport EventEmitter from 'events';const myEmitter = ; // you can also use socket.io as event emitterimport io from 'socket.io-client';const myEmitter = ; { return <EmitterProvider =>...children</EmitterProvider> ;};
useEvent
Use data and the emit function for the specific event.
import React from 'react'; import useEvent from 'use-emitter'; { const message emitMessage = ; const firstMessage = useEvent; return <div> <p>Current message: message</p> <p>First message: firstMessage</p> </div> <input ="text" = = /> </div> ;};
You can also provide the default value of the event as the second parameter of the useEvent function.
const message = ;const firstMessage = useEvent;
useEmit
Use only emit function for the specific event.
import React useState from 'react'; import useEmit from 'use-emitter'; { const messageText setMessageText = ; const emitMessage = ; return <div> <input ="text" = = /> <button => Set message </button> </div> ;}
useEmitter
Use the full instance of the emitter with all of its methods.
; { const emitter = ;}
Additional properties
Additional properties for the on
method.
If the event emitter of your choice expects additional options, you can provide them after the default value.
; { const data emitData = ;} // Event emitter will receive the next arguments:// emitter.on('event-name', callback(), arg1, arg2, arg3)
Additional properties for the emit
method.
If the event emitter of your choice expects additional options or multiple data values, you can provide them as the arguments of the emit function.
; { const data emitData = ; { }} // Event emitter will receive the next arguments:// emitter.emit('event-name', data, arg1, arg2, arg3)