ably-labs / react-hooks Goto Github PK
View Code? Open in Web Editor NEWThe recommended way to use Ably in React components
Home Page: https://www.npmjs.com/package/@ably-labs/react-hooks
License: MIT License
The recommended way to use Ably in React components
Home Page: https://www.npmjs.com/package/@ably-labs/react-hooks
License: MIT License
ably-labs/react-hooks
exports as a ES6 module. Unfortunately, Next.js doesn't transpile functions imported from node_modules. As a result, importing ably-labs/react-hooks
causes an issue (SyntaxError: Unexpected token 'export' with Next.js)
Update the documentation and explain that for Next.js, developers need to install next-transpile-modules and update next.config.js
with:
const withTM = require('next-transpile-modules')(['@ably-labs/react-hooks']);
module.exports = withTM({...})
useChannel doesnt have access to any state.
The data gets refreshed from the server.
When I try to check the data value from the server its undefined. So If i wanted to update state from the ably message I cannot.
const [data, setData] = useState();
configureAbly({ key: ablyClientKey, clientId: "1232" });
const [channel, ably] = useChannel(`channel`, (message) => {
console.log(data) // This is triggered minutes later from the ruby code as data is updated and is always the initialized value not the refreshed value.
});
useEffect(() => {
refreshData()
}, []);
function refreshData() {
axios.get(`/get_data`, { })
.then(res => {
setData(res)
}).catch((error) => {
// Error
console.log(error.response);
})
}
If usePresence
or useChannel
is used without an internet connection (and Ably has not been activated yet), I get this error:
```Error: Ably not configured - please call configureAbly({ key: "your-api-key", clientId: "someid" });``
While I'm sure this might technically be true, it is coming from assertConfiguration
. My expectation is this will fail silently in this scenario.
In general, it is bad form to throw an error inside a hook because it can result in an inconsistent state in the app. Instead it would be preferable to return functions which throw errors - that way the errors can be caught appropriately and dealt with.
Related to #47 - we should ensure that errors aren't thrown inside hooks - these should either be returned from the hook or thrown in a way which can be handled from an error boundary.
Also, as part of this work we should consider the behaviour of useChannel
and usePresence
when a connection/channel error state is reached.
Using a library as a peerDependency offers several advantages, including: reduced bundle size, simpler updates, clear separation between ably react-hooks
and ably-js
This will allow us to see usage of react-hooks
. Refer to the spec (RSC7d) for more details.
I am looking to secure the endpoint that issues my ably tokens. How is this done?
I am using next-auth
With usePresence
, I was trying to call updateStatus
when user information changes, but dropping it in a useEffect
hook was triggering it in a loop since the updateStatus
function changes every render.
Can that function be wrapped in useCallback()
or something to prevent it from triggering updates?
Example of the problem:
const [userData] = useUserData();
const [users, updateStatus] = usePresence('channel-name');
useEffect(()=>{
if ( userData ) updateStatus(userData);
},[userData, updateStatus]); // Infinite loop!
The "solution" right now is to just leave updateStatus
off the dependency array, but that's not ideal since linters and React complain about "exhaustive dependencies".
useEffect(()=>{
if ( userData ) updateStatus(userData);
},[userData]); // No infinite loop
We support React >= 18.1 right now, but React 16 adoption is still big, probably it's better to support React 16.8+
Library publishes several unnecessary files to the final package. We need to remove those files from the package
There's room for improvement to make our linting process even more effective and accurate, including:
eslint-config-airbnb
to devDependencies
Type error: Could not find a declaration file for module '@ably-labs/react-hooks'. '/projects/lmb-saas/web/node_modules/@ably-labs/react-hooks/dist/cjs/index.js' implicitly has an 'any' type.
Try `npm i --save-dev @types/ably-labs__react-hooks` if it exists or add a new declaration (.d.ts) file containing `declare module '@ably-labs/react-hooks';`
> 5 | import { configureAbly } from "@ably-labs/react-hooks";
it didn't happen with 2.0.9
It looks like skip
parameter in useChannel
hook can be useful
References:
See #47 (comment)
These should allow users to listen to connection state along with state errors in a way that is idiomatic for react applications. Ideally these should allow users to control whether a component re-renders upon a given state change.
Provider ignores client created from option right now
I'm using usePresence
like this:
const [presenceData, updateStatus] = usePresence('connect', 'A person name')
I want to have an input to change the message. Something like this:
<input
value={status}
onChange={() => {
// update status
}}
/>
I could use a useState
for status, but I think that would result in duplicate data and could lead to inconsistencies.
Hi,
I just tried the hooks on a very simple project with NextJS. In development, I get an error on HMR (Fast Refresh), because (I think) the connection is closed and open too fast.
Did you already had this issue? Do you know a workaround?
If not, I will be able to provide you a code sandbox 😊
A customer tryed to implement encryption using these hooks: https://ably.com/docs/realtime/encryption
useChannel function doesn't support passing channel options:
https://github.com/ably-labs/react-hooks/blob/main/src/hooks/useChannel.ts#L11-L14
so we'd need to add that as an argument and pass it to channels.get
Currently our tests in this repo are quite rudimentary, a few things we could consider to improve this:
jest
+ @testing-library/react
This is because ably-js channels.get
throws an error when called on the same channel twice with an options param. The solution to this should be to wrap the channels.get
call in a useMemo
.
Hello, So far I have not found a way to force refresh an authentication token to update user claims or clear the instance. The use cases are the following:
The user token is scoped to "workspaces" if the user creates a new workspace or is a new user, the claims need to be updated. There does not currently appear to be a way to do this.
If the user logs out, the token / client ID should be able to be cleared so that if a new user logs in they don't get the same ably instance as the previous user. Currently, a hard refresh of the page is required.
Please let me know if there is a better or existing way to achieve this.
These should allow users to listen to channel state along with state errors in a way that is idiomatic for react applications. Ideally these should allow users to control whether a component re-renders upon a given state change.
I am using the usePresence
hook in my application. My capability is set to only subscribe, so I am unable to call channel.presence.enter()
. In the current implementation of the onMount
function, an error is thrown when calling await channel.presence.enter(messageOrPresenceObject);
, causing the initial presence snapshot not to be fetched.
const onMount = async () => {
channel.presence.subscribe('enter', updatePresence);
channel.presence.subscribe('leave', updatePresence);
channel.presence.subscribe('update', updatePresence);
await channel.presence.enter(messageOrPresenceObject); // add try-catch block here to handle error
const snapshot = await channel.presence.get();
updatePresenceData(snapshot);
}
I have installed ably-labs/react-hooks
in order to use the configureAbly() and useChannel hook in My Next.js app. I created an API endpoint for authentication:
import Ably from "ably/promises";
export default async function handler(req, res) {
const client = new Ably.Realtime(process.env.ABLY_API_KEY);
const tokenRequestData = await client.auth.createTokenRequest({ clientId: 'ably-blog-app' });
res.status(200).json(tokenRequestData);
};
And called configureAbly
in my component:
configureAbly({ authUrl: '/api/createTokenRequest' });
It works fine apart from the fact that I get log messages in my server:
Ably: Auth.requestToken(): token request signing call returned error; err = Error: `input` must not start with a slash when using `prefixUrl`
I have tried removing the slash (this causes an issue) and I have moved the configureAbly
in various places (inside a component, in _app.js
), but it still appears. There is a new one every 30 seconds. Any idea what might cause it?
A key feature of ably is to receive the last message, but the react hook do not expose the history.
https://ably.com/docs/storage-history/storage#persist-last-message
Hi,
I'm seeing this uncaught exception when trying to use the usePresence
hook:
This happens when my component unmounts and the hook tries to leave the channel.
I think my setup might contribute to the problem. Basically I have a component like this:
function MyComponent({ roomId }) {
usePresence(roomId)
}
// Usage
<MyComponent roomId={roomId} key={`${roomId}`}
When the roomId
changes, the component gets re-rendered, which I think causes the channel to start detaching. At the same time, it unmounts, which calls channel.presence.leave
, hence the exception.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.