Only this pageAll pages
Powered by GitBook
1 of 30

phoenix-to-redux

Loading...

Loading...

Loading...

Reference

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Quick Start

This example will quickly connect your phoenix socket, and show the simple basic socket events.

After installation and the setting up of the middleware, you can simply copy this code for your root Saga.

import {
  all,
  call,
  fork,
  put,
  select,
  takeEvery,
  takeLatest,
} from 'redux-saga/effects';
import {
  socketActionTypes,
  connectPhoenix
} from '@trixtateam/phoenix-to-redux';


/**
 * Should the socket attempt to open, this action is dispatched to the
 * phoenix reducer
 * @param {Object} params - parameters
 * @param {string} params.domainKey - domain for socket
 * @param {Object} params.socket = socket being opened
 * @param {boolean} params.params
 */
export function* socketConnectedSaga({ socket,params, domainKey }) {
  console.info('socketConnectedSaga',{ socket,params, domainKey });
}

/** Should an error occur from the phoenix socket, this action will be dispatched
 * @param {Object} params - parameters
 * @param {string} params.error
 * @param {string} params.socketState
 * @param {string} params.domainKey - domain for socket
 */
export function* socketErrorSaga({ error, socketState, domainKey }) {
  // here you should check if your token is valid or not expired, if not
  // disconnect phoenix
  console.error('socketErrorSaga',{ error, socketState, domainKey });
}

/**
 * Should the socket attempt to close, this action is dispatched to the
 * phoenix reducer
 * @param {Object} params - parameters
 * @param {Object} params.socket = socket being closed
 * @param {string} params.domainKey - domain for socket
 * @param {object} params.params - socket.params()
 */
export function* socketCloseSaga({ params, socket, domainKey }) {
  console.info('socketCloseSaga',{ params, socket, domainKey });
}
/**
 * After  phoenix socket disconnects
 * @param {Object} params - parameters
 * @param {Object} params.socket = socket being disconnected
 * @param {string} params.domainKey - domain for socket
 * @param {Object} params.params - socket.params()
 */
export function* socketDisconnectionSaga({ params, socket, domainKey }) {
  console.info('socketDisconnectionSaga',{ params, socket, domainKey });
}


export function* connectSocketSaga() {
  yield put(connectPhoenix({ domainUrl: 'localhost:4000', params: {} }));
}

export default function* defaultSaga() {
yield call(connectSocketSaga);
yield takeEvery(
    socketActionTypes.SOCKET_DISCONNECT,
    socketDisconnectionSaga
  );
  yield takeEvery(socketActionTypes.SOCKET_OPEN, socketConnectedSaga);
  yield takeEvery(socketActionTypes.SOCKET_ERROR, socketErrorSaga);
  yield takeEvery(socketActionTypes.SOCKET_CLOSE, socketCloseSaga);
}

Socket

All the methods and events associated with the socket

Methods
Events

Methods

All the methods associated with the socket

API Reference

Dive into the specifics of each API endpoint by checking out our complete documentation.

See phoenix docs for more detailed information.

Please note all methods need to be dispatched to the redux store either using the

useDispatch hook, the dispatch store function or the put effect in a Saga

Socket Related

All the methods and events associated with the socket

Channel Related

All the methods and events associated with the socket channels

disconnectPhoenix
connectPhoenix
Socket
Channel

Events

All the events associated with the socket

SOCKET_ERROR
SOCKET_OPEN
SOCKET_DISCONNECT
SOCKET_CLOSE
SOCKET_CONNECT

SOCKET_OPEN

Should the socket attempt to open, the following redux event is dispatched

import { socketActionTypes } from '@trixtateam/phoenix-to-redux';
const { SOCKET_OPEN } = socketActionTypes;
Parameter
Description

type

SOCKET_OPEN

socket

phoenix socket

domainKey

endpoint url without socket details or protocol

params

socket connection params

Channel

All the methods and events associated with the socket channels

Methods
Events

Methods

All the methods associated with the socket channels

leavePhoenixChannel
leavePhoenixChannelEvents
leavePhoenixChannelEvent
getPhoenixChannel
pushPhoenixChannel

Events

All the events associated with the socket channels

CHANNEL_ERROR
CHANNEL_LEAVE
CHANNEL_JOIN_ERROR
CHANNEL_JOIN
CHANNEL_TIMEOUT
CHANNEL_PUSH_ERROR
CHANNEL_CLOSE

SOCKET_ERROR

Should an error occur from the phoenix socket, the following redux event is dispatched

import { socketActionTypes } from '@trixtateam/phoenix-to-redux';
const { SOCKET_ERROR } = socketActionTypes;
Parameter
Description

type

SOCKET_ERROR

error

Error response from socket

domainKey

endpoint url without socket details or protocol

socketState

Connection state of socket

CHANNEL_JOIN

After joining a phoenix channel, the following redux event is dispatched.

import { channelActionTypes } from '@trixtateam/phoenix-to-redux';
const { CHANNEL_JOIN } = channelActionTypes;
Parameter
Description

type

CHANNEL_JOIN

channel

Phoenix channel

additionalData

additionalData passed when using

response

Phoenix channel response

getPhoenixChannel

CHANNEL_JOIN_ERROR

Should an error occur from the phoenix socket channel, the following redux event is dispatched. Error response after joining the phoenix channel.

import { channelActionTypes } from '@trixtateam/phoenix-to-redux';
const { CHANNEL_JOIN_ERROR } = channelActionTypes;
Parameter
Description

type

CHANNEL_JOIN_ERROR

channelTopic

Name of channel/Topic

channel

Phoenix channel

additionalData

additionalData passed when using

error

Phoenix channel error

getPhoenixChannel

CHANNEL_TIMEOUT

Should an error occur from the phoenix socket channel, the following redux event is dispatched. Timeout error response after joining the phoenix channel.

import { channelActionTypes } from '@trixtateam/phoenix-to-redux';
const { CHANNEL_TIMEOUT } = channelActionTypes;
Parameter
Description

type

CHANNEL_TIMEOUT

channelTopic

Name of channel/Topic

channel

Phoenix channel

additionalData

additionalData passed when using

error

Phoenix channel error

getPhoenixChannel

SOCKET_CLOSE

Should the socket attempt to close, the following redux event is dispatched

import { socketActionTypes } from '@trixtateam/phoenix-to-redux';
const { SOCKET_CLOSE } = socketActionTypes;
Parameter
Description

type

SOCKET_CLOSE

socket

phoenix socket

domainKey

endpoint url without socket details or protocol

params

socket connection params

CHANNEL_PUSH_ERROR

Should an error occur from the phoenix socket channel, the following redux event is dispatched. Error response after pushing data to phoenix channel.

Parameter
Description
import { channelActionTypes } from '@trixtateam/phoenix-to-redux';
const { CHANNEL_PUSH_ERROR } = channelActionTypes;

type

CHANNEL_PUSH_ERROR

channelTopic

Name of channel/Topic

channel

Phoenix channel

error

Phoenix channel error

disconnectPhoenix

This method will disconnect the phoenix socket

import { disconnectPhoenix } from '@trixtateam/phoenix-to-redux';

Parameters

None

Installation

You can install phoenix-to-redux with NPM or Yarn

Using Yarn Package Manager is recommended over npm.

yarn add @trixtateam/phoenix-to-redux
npm i @trixtateam/phoenix-to-redux

1. Setup Phoenix Reducer

Include the phoenix reducer into your combined reducer

import { combineReducers } from 'redux';
import { phoenixReducer } from '@trixtateam/phoenix-to-redux';

export default function createReducer() {
  const rootReducer = combineReducers({
    phoenix: phoenixReducer,
  });
  return rootReducer;
}

2. Setup Phoenix Middleware

Example below for including the phoenix-to-redux middleware into your application. see redux docs, for more info on setting up your store.

Please note the sagaMiddleware used below is not required, this is just what is being use in the example below to intercept all redux actions.

import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit';
import { createPhoenixChannelMiddleware } from '@trixtateam/phoenix-to-redux';
import createSagaMiddleware from 'redux-saga';
import rootSaga from './rootSaga';
import createReducer from './reducers';


export default function configureStore(initialState = {}) {
  const reduxSagaMonitorOptions = {};
  // Makes redux connected to phoenix channels
  const phoenixChannelMiddleWare = createPhoenixChannelMiddleware();
  const sagaMiddleware = createSagaMiddleware(reduxSagaMonitorOptions);
  const middlewares = [sagaMiddleware,phoenixChannelMiddleWare];

  const enhancers = [];

  const store = configureStore({
    reducer: createReducer(),
    middleware: [
      ...getDefaultMiddleware({
        thunk: false,
        immutableCheck: {
          ignore: ['socket', 'channel', 'trixta', 'phoenix', 'router'],
        },
        serializableCheck: false,
      }),
      ...middlewares,
    ],
    devTools:
      /* istanbul ignore next line */
      process.env.NODE_ENV !== 'production' ||
      process.env.PUBLIC_URL.length > 0,
    enhancers,
  });

  sagaMiddleware.run(rootSaga);

  return store;
}

3. Dispatch a connectPhoenix event

Below is just quick simple React App example

import * as React from 'react';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import {
  connectPhoenix
} from '@trixtateam/phoenix-to-redux';
import Providers from './Providers';
import Routes from './Routes';


export function App() {
const dispatch = useDispatch();
useEffect(() => {
    dispatch(connectPhoenix({ domainUrl:'localhost:4000', params: {} }))
  }, [dispatch]);
  
return (<Providers>
      <Routes />
    </Providers>)

}

export default App;

connectPhoenix

This method will setup and connect the phoenix socket

import { connectPhoenix } from '@trixtateam/phoenix-to-redux';

Parameters

Parameter
Description
Type
Required

domainUrl

socket endpoint to connect to

string

params

optional parameters to pass when connecting to socket

any

options

optional configuration options

SOCKET_DISCONNECT

Should the socket attempt to disconnect, the following redux event is dispatched

Parameter
Description

leavePhoenixChannelEvents

This method will unsubscribe for the given events for the given channelTopic

Parameters

Parameter
Description
Type
Required

SOCKET_CONNECT

Should the socket attempt to connect, the following redux event is dispatched

Parameter
Description
import { socketActionTypes } from '@trixtateam/phoenix-to-redux';
const { SOCKET_DISCONNECT } = socketActionTypes;

type

SOCKET_DISCONNECT

socket

phoenix socket

domainKey

endpoint url without socket details or protocol

params

socket connection params

import { leavePhoenixChannelEvents } from '@trixtateam/phoenix-to-redux';

channelTopic

Name of channel/Topic

string

events

Array of event names to unsubscribe to

string []

import { socketActionTypes } from '@trixtateam/phoenix-to-redux';
const { SOCKET_CONNECT } = socketActionTypes;

type

SOCKET_CONNECT

socket

phoenix socket

domainKey

endpoint url without socket details or protocol

options

CHANNEL_CLOSE

Should a phoenix channel be explicitly closed on the server or the channel was explicitly closed by calling channel.leave(). The following redux event is dispatched

import { channelActionTypes } from '@trixtateam/phoenix-to-redux';
const { CHANNEL_CLOSE } = channelActionTypes;
Parameter
Description

type

CHANNEL_CLOSE

channel

Phoenix channel

getPhoenixChannel

This method will subscribe phoenix channel for the given channelTopic and given events

import { getPhoenixChannel } from '@trixtateam/phoenix-to-redux';

Recommended that you already have made a socket connection by using connectPhoenix method before using this method.

Parameters

Parameter
Description
Type
Required

channelTopic

Name of channel/Topic

string

logPresence

Determines if presence should be tracked for the channel

boolean

token

private token for channel

string

additionalData

This data will be available for you as additionalData on the response

object

events

Array of event names to subscribe to and will dispatch response to eventActionType

{

eventName:string; eventActionType:string

} []

domainUrl

socket endpoint to connect to

string

CHANNEL_ERROR

Should an error occur from the phoenix socket channel, the following redux event is dispatched. Invoked if the socket connection drops, or the channel crashes on the server.

import { channelActionTypes } from '@trixtateam/phoenix-to-redux';
const { CHANNEL_ERROR } = channelActionTypes;
Parameter
Description

type

CHANNEL_ERROR

channelTopic

Name of channel/Topic

channel

Phoenix channel

leavePhoenixChannel

This method will leave the phoenix channel for the given channelTopic and unsubscribes off of channel events

import { leavePhoenixChannel } from '@trixtateam/phoenix-to-redux';

Parameters

Parameter
Description
Type
Required

channelTopic

Name of channel/Topic

string

CHANNEL_LEAVE

After phoenix channel is left. The following redux event is dispatched

import { channelActionTypes } from '@trixtateam/phoenix-to-redux';
const { CHANNEL_LEAVE } = channelActionTypes;
Parameter
Description

type

CHANNEL_LEAVE

channel

Phoenix channel

pushPhoenixChannel

This method will attempt to find the subscribed phoenix channel for the given channelTopic and push data to the channel for the eventName.

import { pushPhoenixChannel } from '@trixtateam/phoenix-to-redux';

Recommended that you already have made a socket connection by using connectPhoenix method before using this method.

Parameters

Parameter
Description
Type
Required

channelTopic

Name of channel/Topic

string

eventName

Name of the event on channel to push to

string

requestData

Payload data to push on the channel

any

additionalData

This data will be available for you as additionalData on the response

object

loadingStatusKey

A unique identifier you can use to separate progress status

string

endProgressDelay

timeout in milliseconds if you want to delay the endProgress of your loadingStatusKey

number

channelResponseEvent

name of redux event to dispatch to reducer on response from pushing to channel

string

channelErrorResponseEvent

name of redux event to dispatch to reducer on error from pushing to channel

string

channelTimeOutEvent

name of redux event to dispatch to reducer on timeout from pushing to channel

string

dispatchChannelError

false by default, determines if should an on channel error occur dispatch to the reducer

boolean

channelPushTimeOut

timeout in milliseconds for pushing to the channel, default is 1500

number

Overview

phoenix-to-redux is a redux-store middleware that integrates phoenix socket communication with the redux store using redux actions.

Welcome to phoenix-to-redux

Welcome to phoenix-to-redux! Here you'll find all the documentation you need to get up and running with the phoenix-to-redux.

Want to deep dive?

Dive a little deeper and start exploring our API reference to get an idea of everything that's possible with the package:

leavePhoenixChannelEvent

This method will unsubscribe for the given event for the given channelTopic

Parameters

Parameter
Description
Type
Required
import { leavePhoenixChannelEvent } from '@trixtateam/phoenix-to-redux';

channelTopic

Name of channel/Topic

string

event

Event name to unsubscribe to

string

PHOENIX_CHANNEL_ERROR
API Reference
GitHub - trixtateam/phoenix-to-redux: Intergrate phoenix channels with react redux reducerGitHub
Github Repository
Logo