Git Product home page Git Product logo

react-hooks's Issues

SyntaxError: Unexpected token 'export' with Next.js

Context

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)

Possible Fix

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 Borked

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);
      })
  }

usePresence throws error if Ably is not configured

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.

Reconsider error handling strategy

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.

Use `ably-js` as peer dependency

Using a library as a peerDependency offers several advantages, including: reduced bundle size, simpler updates, clear separation between ably react-hooks and ably-js

`usePresence`: `updateStatus` changes every render

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

2.0.10 throws typescript errror

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

Add hook for listening to connection state

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.

How to catch failed rest error

Heya, so we're getting this log (I think due to brave browser blocking requests) - it does eventually connect (as the error code associated with this log says it will keep retrying), but ideally we'd catch the log and squash it.

Where do I catch this error?

Get the current message in `usePresence`

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.

Issue with HMR (Fast Refresh) in NextJS

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.

image

Did you already had this issue? Do you know a workaround?

If not, I will be able to provide you a code sandbox 😊

Improve test coverage

Currently our tests in this repo are quite rudimentary, a few things we could consider to improve this:

  • adding unit tests
  • migrating from vitest to a more mature setup using jest + @testing-library/react
  • adding tests with a live connection using the sandbox env

FEATURE: A way to force refresh the token, or clear the existing instance / client

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.

Add hook for listening to channel state

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.

`usePresence` hook fails to get initial snapshot when capability is only subscribe

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);
}

Auth.requestToken(): `input` must not start with a slash when using `prefixUrl`

Context

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?

Channel operation failed as channel state is detaching

Hi,

I'm seeing this uncaught exception when trying to use the usePresence hook:

Screenshot 2022-08-11 at 00 20 11

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.