Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Manage client changes passing a callback instead of using event emitter #10

Open
singiamtel opened this issue Aug 29, 2023 · 0 comments

Comments

@singiamtel
Copy link
Owner

singiamtel commented Aug 29, 2023

Doing it this way we shouldn't have any re-render issues as we're not trying to get stale variables from client

Example snippet on how the callback should look by @Async10

type PS = {
	rooms: Room[]
	users: User[]
	send(roomId: string, message: string): void
}

const PSContext = React.createContext<PS | null>(null)

type PSProviderProps = {
	client: PSClient
	children: React.ReactNode
}

function PSProvider(client: PSClient) {
	const [users, setUsers] = React.useState<User[]>([])
	const [rooms, setRooms] = React.useState<Room[]>([])

	React.useEffect(() => {
		client.connect()
		client.subscribe(handlePSEvent)
	}, [handlePSEvent])

	const handlePSEvent = React.useCallback(function (event: PSEvent) {
		// TODO: Handle PSEvent and update users and roooms by
		// using setUsers and setRooms
	}, [setUsers, setRooms])

	
	return (
		<PSContext.Provider value={{ rooms, users, send: client.send }}>
			{props.children}
		</PSContext.Provider>
	)
}

function usePS() {
	const ps = React.useContext(PSContext)
	if (!ps) throw new Error("You fucked up. Pass an instance of PSClient to PSProvider!")
	return ps
}

const client = new PSClient(...)

function App() {
	<PSProvider client={client}>
		{/* Components ... */}
	</PSProvider>
}
@singiamtel singiamtel converted this from a draft issue Aug 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: To do
Development

No branches or pull requests

1 participant