DEV Community

Mark Nefedov
Mark Nefedov

Posted on

Integrate Elxir Phoenix client with JS app.

If you have an existing JavaScript or TypeScript application, and you’d like to add a Phoenix JavaScript client to it, you can do so by following these steps:

  1. Install the Phoenix JavaScript client by running the following command in your React project’s directory:
npm install --save phoenix
Enter fullscreen mode Exit fullscreen mode
  1. In your React application, you’ll need to import the Socket and LongPoll modules from the phoenix package, as well as the phoenix package itself. For example:
import {Socket} from "phoenix"
Enter fullscreen mode Exit fullscreen mode
  1. Create a new instance of the Socket class, passing in the URL of your Phoenix server’s endpoint as the first argument.
let socket = new Socket("ws://localhost:4000/socket");
Enter fullscreen mode Exit fullscreen mode
  1. Connect to the socket by calling the connect method on the socket object. For example:
socket.connect();
Enter fullscreen mode Exit fullscreen mode
  1. Once the socket is connected, you can join channels and bind to events to receive messages from the server. For example, you can join a channel named “room:lobby” and listen for the “new_msg” event like this:
let channel = socket.channel("room:lobby", {});
channel.join()
  .receive("ok", resp => { console.log("Joined successfully", resp) })
  .receive("error", resp => { console.log("Unable to join", resp) });

channel.on("new_msg", payload => {
  console.log(payload);
});
Enter fullscreen mode Exit fullscreen mode
  1. To send a message back to the server over this channel, you can use push method:
channel.push("new_msg", {body: "This is a test message"});
Enter fullscreen mode Exit fullscreen mode

With these steps, you should now be able to interact with your Phoenix server using the JavaScript client in your React application.

Please keep in mind that you might have to modify the server side to handle new_msg event, depend on your server implementation.

Typescript

You can install the @types/phoenix package, which provides the TypeScript declarations for the Phoenix client. You can do this by running the following command in your project’s directory:

npm install --save-dev @types/phoenix
Enter fullscreen mode Exit fullscreen mode

This package provides TypeScript declarations for the Phoenix JavaScript client, so that you can take advantage of TypeScript’s type checking and editor support when working with the Phoenix client in your application.

You could also use some pre-built package like phoenix-ts that is written in Typescript, but this is not an official library of phoenix.

It’s also worth noting that these packages may be updated less frequently than the official phoenix package, so you may want to keep an eye on that and consider updating if necessary.

Top comments (0)