{"id":15896711,"url":"https://github.com/msutkowski/twilio-client-redux","last_synced_at":"2025-03-20T15:33:09.269Z","repository":{"id":42898844,"uuid":"252327921","full_name":"msutkowski/twilio-client-redux","owner":"msutkowski","description":"Redux bindings for Twilio Client JSSDK","archived":false,"fork":false,"pushed_at":"2023-01-06T02:46:12.000Z","size":748,"stargazers_count":2,"open_issues_count":17,"forks_count":2,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-16T00:27:48.513Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/msutkowski.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-04-02T01:41:13.000Z","updated_at":"2023-03-09T02:53:01.000Z","dependencies_parsed_at":"2023-02-05T03:46:40.439Z","dependency_job_id":null,"html_url":"https://github.com/msutkowski/twilio-client-redux","commit_stats":null,"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/msutkowski%2Ftwilio-client-redux","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/msutkowski%2Ftwilio-client-redux/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/msutkowski%2Ftwilio-client-redux/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/msutkowski%2Ftwilio-client-redux/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/msutkowski","download_url":"https://codeload.github.com/msutkowski/twilio-client-redux/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244640375,"owners_count":20486029,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-06T09:21:35.688Z","updated_at":"2025-03-20T15:33:08.904Z","avatar_url":"https://github.com/msutkowski.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Twilio Client Redux\n\n## Purpose\n\nThis package is intended to be used with [`twilio-client.js`](https://github.com/twilio/twilio-client.js) and to make integrating its event emitters with redux very straightforward. We recommend using it along side [Redux Toolkit](https://github.com/reduxjs/redux-toolkit) for several reasons and all code examples are shown with RTK implementations.\n\nThe general implementation of this library is currently very opinionated, but should work for every use case - if you have any specific requests, please open an issue or PR and we'd be happy to include it. Our goal is to track `twilio-client` releases and upgrade as necessary.\n\n\u003e Note: As of right now, Twilio does not export types that are easily consumable in their frontend libraries, but we do our best to give you an accurate representation of the serializable **device** and **connection** when appropriate. This is mostly just for logging purposes as you can't call methods on the serialized `Device` or `Connection` objects.\n\n## Installation\n\nUsing `npm`:\n\n```\nnpm i twilio-client-redux\n```\n\nUsing `yarn`:\n\n```\nyarn add twilio-client-redux\n```\n\n## Usage\n\n### Add the middleware\n\nAt a high level, the implementation looks like this:\n\n1.  Add the middleware\n2.  Create a device instance with your capability token by `dispatch`ing `setup(token, options)`\n3.  `dispatch` actions to make calls, control the device, etc etc.\n4.  Respond to events in relevant reducers to handle `Device` and/or `Connection` events\n5.  Have a phone party!\n\nThe middleware accepts the following options:\n\n```ts\nexport interface MiddlewareOptions {\n  storeAudioDevices?: boolean; // default = true. store the payload of setInputDevice/setOutputDevice to localStorage. will automatically try to use the values when setting up a future device.\n  connectOnIncoming?: boolean; // default = true. automatically accept incoming connections\n  prefix?: string; // default = @tcr. currently unimplemented and may be implemented in the future\n}\n```\n\nExample implementation:\n\n```ts\n// store.ts\n\nimport { configureStore, Action, getDefaultMiddleware } from '@reduxjs/toolkit';\nimport TwilioClientRedux from 'twilio-client-redux';\n\nimport rootReducer, { RootState } from './rootReducer';\n\nconst store = configureStore({\n  reducer: rootReducer,\n  middleware: [...getDefaultMiddleware(), TwilioClientRedux()],\n});\n\nexport type AppDispatch = typeof store.dispatch;\n\nexport default store;\n```\n\n### Initialize a device\n\n```ts\n// MyPhoneApp.ts\nimport React, { useEffect } from \"react\";\nimport { useDispatch, useSelector } from \"react-redux\";\nimport { setup } from \"twilio-client-redux\";\n\nexport const MyPhoneApp = () =\u003e {\n\nconst dispatch = useDispatch();\n\nuseEffect(() =\u003e {\n  // You could fetch a token here, or pass it in as a prop, or whatever makes sense for your app\n    dispatch(setup(token, { debug: true }));\n}, [token])\n});\n\nreturn (\u003cPhoneUI /\u003e);\n\n};\n```\n\n#### Device setup options:\n\nAccepts the standard `twilio-client` `Device` options:\n\n```ts\ndeclare interface DeviceConfigOptions {\n  allowIncomingWhileBusy?: boolean;\n  audioConstraints?: MediaTrackConstraints | boolean;\n  closeProtection?: boolean | string;\n  codecPreferences?: Codec[];\n  debug?: boolean;\n  disableAudioContextSounds?: boolean;\n  dscp?: boolean;\n  enableIceRestart?: boolean;\n  enableRingingState?: boolean;\n  fakeLocalDTMF?: boolean;\n  forceAggressiveIceNomination?: boolean;\n  maxAverageBitrate?: number;\n  region?: string;\n  rtcConfiguration?: RTCConfiguration;\n  sounds?: Partial\u003cRecord\u003cSoundName, string\u003e\u003e;\n  warnings?: boolean;\n}\n```\n\n#### Device actions:\n\n\u003e Note: All devices actions take an optional parameter of `deviceId`. By default, this is set to 'default'. This allows you to manage multiple devices if your implementation requires that.\n\n```ts\nsetup(); // initialize a device.\ndestroy(); // destroy the device instance and disconnect all connections. you will need to call setup again to create a new device.\nsetOutputDevice(); // if you passed in storeAudioDevices: true to `setup`, this will store in localStorage. it will attempt to be reused when the device initialized in the future\nsetInputDevice(); // sets the input device and behaves the same as setOutputDevice\ntestOutputDevice(); // can be used to play a chime on the currently set output device\n```\n\n### Managing connections\n\nWe provide every method that is available to `twilio-client.js` as exported actions. All methods take an optional `deviceId` parameter.\n\n```ts\nmakeCall();\nhangupCall();\nsendDigit(); // sends a digit to the active connection\n\nsetMute(); // mute the current connection on the device\ntoggleMute(); // toggles the mute state\ngetMuteStatus(); // returns `{ muted: value }`\n\ngetStatus(); // returns the status of the active connection\n\nacceptCall();\nrejectCall();\nignoreCall();\n```\n\n## Responding to middleware-generated actions in a reducer\n\nBy default, the middleware creates actions for every `twilio-client` event listener. Depending on your redux setup, you can append `.type` to the end of the action you're looking for to get it's type value (ex: `onReady.type` === `@tcr::DEVICE_READY`).\n\nIn a non-`createSlice` implementation, that might look like:\n\n```js\n// phoneReducer.js\n// ... reducer code\nswitch (action.type) {\n  case onReady.type:\n  // Do things when the device is ready\n}\n```\n\n### Included action types that are created after initializing a Device\n\n```ts\nonReady;\nonCancel;\nonConnect;\nonError;\nonDisconnect;\nonIncoming;\nonOffline;\n```\n\nExample slice responding to common use cases:\n\n```ts\n// phoneSlice.ts\n\nimport { createSlice, createAsyncThunk } from '@reduxjs/toolkit';\nimport {\n  onReady,\n  onConnect,\n  onDisconnect,\n  getMuteStatus,\n} from 'twilio-client-redux';\nimport { RootState } from 'src/store/rootReducer';\nimport { apiRequest } from 'src/utils';\n\n// in this case, we make an API request to our server to initiate a call. being that\n// the default value in the middleware is to automatically accept incoming connections\n// our call will be bridged immediately. your implementation will vary.\nexport const makeCall = createAsyncThunk(\n  'phone/makeCall',\n  async (phone: string) =\u003e {\n    const {\n      data: { data },\n    } = await apiRequest.post\u003cCall\u003e(`agent/calls`, { phone });\n    return data;\n  }\n);\n\nconst initialState = {\n  call: {},\n  muted: false,\n  status: 'idle',\n};\n\nconst slice = createSlice({\n  name: 'phone',\n  initialState,\n  reducers: {},\n  extraReducers: builder =\u003e {\n    builder.addCase(onReady, (state, action) =\u003e {\n      // Note that action is type safe here and will return a serialized `Device`\n      state.status = 'idle';\n    });\n    builder.addCase(onConnect, (state, action) =\u003e {\n      // Note that action is type safe here and will return a serialized `Connection`\n      state.status = 'active';\n    });\n    builder.addCase(onDisconnect, (state, action) =\u003e {\n      // Note that action is type safe here and will return a serialized `Device`\n      return initialState;\n    });\n    builder.addCase(makeCall.pending, (state, action) =\u003e {\n      // set state to ringing when we initiate the API request to start the call\n      state.status = 'ringing';\n    });\n    builder.addCase(makeCall.fulfilled, (state, action) =\u003e {\n      // Note that action is type safe here and will return a action.payload will be the type of Call from our API\n      state.status = 'active';\n      state.call = action.payload;\n    });\n    builder.addCase(getMuteStatus, (state, action) =\u003e {\n      state.muted = action.payload.muted;\n    });\n  },\n});\n\nexport default slice.reducer;\n\nexport const selectIsMuted = (state: RootState) =\u003e state.phone.muted;\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmsutkowski%2Ftwilio-client-redux","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmsutkowski%2Ftwilio-client-redux","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmsutkowski%2Ftwilio-client-redux/lists"}