Integrate Elxir Phoenix client with JS app.
Mark Nefedov
Posted on May 16, 2023
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:
- Install the Phoenix JavaScript client by running the following command in your React project’s directory:
npm install --save phoenix
- In your React application, you’ll need to import the
Socket
andLongPoll
modules from thephoenix
package, as well as thephoenix
package itself. For example:
import {Socket} from "phoenix"
- 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");
- Connect to the socket by calling the
connect
method on the socket object. For example:
socket.connect();
- 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);
});
- 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"});
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
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.
Posted on May 16, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.