A React client for RTDS Server, which is a live query server providing automatic updates for changed rows in database after any query. The example below assumes the server described in the RTDS-Server documentation.
A single client instance is provided by the library. In order to configure it, you need to set the server port handling the socket IO calls. Currently only the same server is supported.
import { client } from 'rtds-client';
client.configure({port: 2999});
One can check if the client has logged in with the hook
import { useLoginStatus } from 'rtds-client';
const isLoggedIn = useLoginStatus();
This can be used to decide if the login page is to be shown instead of the application. Once the credentials are collected, the client can authenticate
await client.login({user: 'user', password: 'pass'});
and then redirect to the starting page.
All data reading and manipulation is done using hooks. For example, to read data from the given channel and rendering it is essentially done with
import { useDataRead} from 'rtds-client';
function TodoList() {
const [todos, setTodos] = useState([]);
useDataRead('todos', setTodos);
return <ul>
{todos.map(todo => <li key={todo.id}>{todo.isDone ? '[X]' : '[ ]'} {todo.title}</li>)}
</ul>;
}
Whenever data has been changed since initial call, it is automatically updated on the screen. The hook handles automatically subscribing and unsubscribing from the given channel.
Additional conditions to the data reader hook, is also possible. For example fetching single todo entry from the detailed singular channel
const [todo, setTodo] = useState([{}]);
useDataRead('todo', `id=${props.todoId}`, setTodo);
A data creation hook is used as the following
import { useDataCreation } from 'rtds-client';
const create = useDataCreation();
create({ todos: {title: "New Title" }});
Function generated by the hook is called with the object having channel names as keys and either single object or an array of objects to create.
Updating is similar to creation except the primary key(s) must be defined in the data. Only defined columns are updated. The rest are kept as they are.
import { useDataUpdate } from 'rtds-client';
const update = useDataUpdate();
update({ todos: {id: 2, title: "Updated Title" }});
A hook to delete
import { useDataDelete } from 'rtds-client';
const del = useDataDelete();
del({ todos: {id: 2});
is similar to update, but only needs primary key or other field defined in the server-side query.
There is a simple example that can be used out of the box with the RTDS Server.
cd example
npm install
npm start