Skip to content

flakevine/use-channel

Repository files navigation


useChannel

Make React-Query realtime for all of your clients with one extra line of code

AboutKey FeaturesGetting StartedFAQRoadmapLicense

About

Make React-Query realtime for all of your clients with one extra line of code

Key Features

  • Sync all your clients with the backend's data
    • When data from backend changes, clients are notified and revalidates the current data
  • Plug and play, you can easily add it to an existing code using react-query to add realtime functionality between clients
  • Simple API
  • Simple configuration
  • You can achieve type-safety between your client and server by using trpc's client functions instead of fetch or axios on the QueryFn or MutationFn

Getting Started

Side note: Currently this library is written in TypeScript and it hasn't been compiled yet, so we only support for TypeScript clients, we are working to fix this issue

For this to work properly, you need a working PubSub solution for syncing events between the client and server, currently we only support Nats, however other systems are going to be implemented on the future.

Prerequisites

  • Node.js with a package manager (npm, yarn or pnpm)
  • React with TypeScript
  • Tanstack Query installed on React
  • Some PubSub system supported by this lib (nats)

Installing and Running

First make sure you have React, Tanstack Query and some supported PubSub system,

Then install @flakevine/use-channel using your prefered package manager.

# if you use npm
$ npm install @flakevine/use-channel
# if you use yarn
$ yarn add @flakevine/use-channel
# if you use pnpm
$ pnpm install @flakevine/use-channel

Use the Context Provider on your app root component:

<ChannelContextProvider opts={{ provider: "nats", url: "ws://localhost:4444" }}>
  <App />
<ChannelContextProvider/>

Then you can already use our hooks!


Client-side code (React with TypeScript and configured Tanstack Query)

import { useChannel } from "@flakevine/use-channel";
import { useState } from "react";
import type { ChangeEvent, FormEvent } from "react";

type BookMutationData = {
  bookName: string;
};

const apiUrl = "http://localhost:3000";

const booksQuery = () => {
  return fetch(apiUrl, {
    method: "GET",
    headers: { "Content-Type": "application/json" },
  }).then((res) => res.json());
};

const booksMutation = (data: BookMutationData) => {
  return fetch(apiUrl, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data),
  });
};

export default function App() {
  const { channel, mutation, query } = useChannel(
    ["books"],
    booksQuery,
    booksMutation
  );
  const [bookName, setBookName] = useState("");

  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    mutation.mutate({ bookName });
  };

  const handleInput = (event: ChangeEvent<HTMLInputElement>) => {
    setBookName(event.target.value);
  };

  if (channel.isConnecting || query.isLoading) return <div>Loading...</div>;

  return (
    <div>
      <h1>useChannel Test</h1>
      {JSON.stringify(query.data)}

      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={bookName}
          onChange={handleInput}
          placeholder="The name of the book"
        />
        <button type="submit">Create book</button>
      </form>
    </div>
  );
}

Server-side code (Node.js with TypeScript and Express)

import express from 'express';
import cors from 'cors';

const app = express();
const port = 3000;

app.use(express.json());
app.use(cors());

const books: string[] = []

app.get('/', (req, res) => {
  res.json(books)
})

app.post('/', (req, res) => {
  const { bookName } = req.body;
  books.push(bookName);
  res.json(books)
})

app.listen(port, () => {
  console.log(`listening on port ${port}`);
})

FAQ

Is it any good?

yes.

Roadmap

  • Add this README.
  • Build this and publish it to npmjs (add support for JavaScript)
  • Support for Redis

Emailware

[Project's name] is an emailware. Meaning, if you liked using this app or it has helped you in any way, I'd like you send me an email at [email protected] about anything you'd want to say about this software. I'd really appreciate it!

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

MIT


GitHub @flakevine

About

Make React-Query realtime for all of your clients with one extra line of code

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published