Reactive variables
Observable global state management for React. This project was inspired by jorbuedo's react-reactive-var
.
Install
npm i @yanfoo/react-var --save
yarn add @yanfoo/react-var
pnpm i @yanfoo/react-var
Usage
import reactVar from "@yanfoo/react-var";
type User = {
id: number;
username: string;
};
type UserAuthStatus = {
user: User | null;
error: string | null;
};
export const activeUser = reactVar<UserAuthStatus>(
{ user: null, error: null },
{
comparator: (a, b) => a.user?.id === b.user?.id && a.error === b.error,
}
);
export const authenticator = {
login: (username: string, password: string): void => {
setTimeout(() => {
if (password === "1234") {
activeUser({ user: { id: 1, username }, error: null });
} else {
activeUser(({ user }) => ({
user,
error: "Invalid username or password",
}));
}
}, 200);
},
logout: () => {
activeUser({ user: null, error: null });
},
};
import React from "react";
import { authenticator, activeUser } from "./auth";
export default () => {
const userRef = React.useRef<HTMLInputElement>(null);
const passRef = React.useRef<HTMLInputElement>(null);
const handleLogin = () =>
authenticator.login(userRef.current?.value, passRef.current?.value);
return (
<div>
<div>
Currently authenticated user : <UserLabel />
</div>
<AuthMessage />
<div>
<label for="username">Username</label>
<input id="username" type="text" ref={userRef} />
</div>
<div>
<label for="username">Password</label>
<input id="username" type="password" ref={passRef} />
</div>
<div>
<button onClick={handleLogin}>Login</button>
</div>
</div>
);
};
const UserLabel = () => {
const username = activeUser.useValue(({ user }) => user?.username ?? null);
return username ?? "Guest";
};
const AuthMessage = () => {
const message = activeUser.useValue(({ error }) => error ?? null);
return message ? <div>{message}</div> : null;
};
Limitations
Setting a new values to a ReactVar
can be made asynchronously. Meaning that any
modification will cause parallel modifications to be stacked and processed
sequentially. However, trying to modify a ReactVar
within a subscriber callback
will fail, and this is in order to prevent race conditions, where the subscriber
and the setter would wait for each other to complete, creating a dead lock situation.
Example
const myVar = reactVar();
myVar.subscribe(({ value }) => {
myVar(value + 1);
});
myVar(0);
Workaround
The subscription handler provides an after
function to invoke a callback
when the mutation has settled. This callback is called asynchronously, and
allows to immediately modify the ReactVar
instance. If used, this feature
should include an exit condition as it will trigger updates as long as the
value is evaluated as different by the comparator
; using this feature
should be avoided if possible.
const myVar = reactVar(0, {
comparator: (a, b) => Math.abs(a - b) < 0.5,
});
myVar.subscribe(({ value, after }) => {
after(() => {
myVar(myVar.value / 2);
});
});
myVar(16);
Contribution
All contributions welcome! Every PR must be accompanied by their associated unit tests!
License
MIT