coderoyalty / pseudonym-app

An anonymous messaging application
https://pseudonym-app.vercel.app
MIT License
2 stars 0 forks source link

Don't use the callback name to identify duplicates callbacks #13

Closed coderoyalty closed 8 months ago

coderoyalty commented 8 months ago

The sole goal of the AuthObserver class is to create a loose way for components to act on a specific event that is triggered. Any component (technically living under the auth context) can access the observer via const {observer} = useAuth();.

Issue 1

Except that here: https://github.com/coderoyalty/pseudonym-app/blob/032edd7f138512291d91ce42ca342d8b1757e853/app/src/contexts/auth.tsx#L39

An anonymous function (a function without a name) will exploit the goal of this application. Here's how.

observer.subscribe("unauthorized_access", () => {console.log("unauthorized access"));
observer.subscribe("unauthorized_access", () => {console.log("unauthorized access 2"));

The first observer will be subscribed, while the second anonymous function will be considered a duplicate of the first one, although there are no duplicates.

Solution: since JS/TS functions are objects, we can compare them directly.

Optimization

An observer should provide a method to unsubscribe a callback from it. Concerning the application, a component can subscribe to an observer immediately after it is mounted and unsubscribe when it unmounts.

Example here:

const observe = () => {
    signout();
    toast({
      title: "Uh oh! You can't visit this page!",
      description: "We're sorry, but you have to signup/login to see this page",
    });
    navigate("/");
  };

  React.useEffect(() => {
    observer.subscribe("invalid_session", observe);

    return () => {
      observer.unsubscribe("invalid_session", observe);
    };
  }, []);