Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Request communication-state tracker, pluggable into redux.

License

NotificationsYou must be signed in to change notification settings

MatthiasMargot/redux-communication

Repository files navigation

Request communication-state tracker that's pluggable intoredux.

npm versionMaintainabilityKnown Vulnerabilities


Definition ofcommunication-state in the scope of this library:

Communication state is the transitional state that a request communicating with an external source has to go through from initiation to completion.The transitionary sub-states of communication-state commonly include: in-flight (fetching/loading) failed-state (represented by an error) and success-state (represented by a successful response)

Redux-Communication removes the need for you to worry about boilerplate-heavy communication-state handling that is necessary to represent any request transitions in you redux-application by generalizing the following:

  • Dispatchingrequested,error andsuccess actions
  • Storingfetching,error andresponse states in your redux-store
  • Creating the selector necessary to get the communication-state of any given request from your state
  • Creating the action-creator needed to trigger your request
  • Creating the action-types for the events occurring during a given request's life-cycle

By having all of these automatically generated and handled by the reducer-middleware-duo, your code is left with much less redux request-handling-boilerplate & you'll have much less pesky asynchronous code to test.

Table of contents


Installation

Install from thenpm registry

npm i redux-communication

UsecreateCommunication to create a [ middleware, request ] tuple and plug it into redux.

import{createStore,combineReducers,applyMiddleware}from'redux'import{createCommunication}from'redux-communication'const[communicationMiddleware,communicationReducer]=createCommunication()/* * redux-communication makes the assumption that your communication-state * is situated under the key 'communication' so make sure you map the * returned communicationReducer to that key */constreducer=combineReducers({communication:communicationReducer})conststore=createStore(reducer,applyMiddleware(communicationMiddleware))

Usage

Creating a request

UsecreateRequest to create the following tuple

[ requestActionCreator, requestCommunicationSelector, requestActionTypes ]
import{createRequest}from'redux-communication'constdataRequest=createRequest('data',id=>fetch(`https://my-api.com/v1/data/${id}`),)/* * export and use in a different file (for example from a React-Component * connected with 'react-redux's 'connect()') to trigger the request in * the middleware */exportconst[requestData]=dataRequest

In this examplerequestData is an action-creator that will trigger the actual call for the data to be executed.

The actual request-function requires anid argument in this example, to make sure that the fetch-caller function receives that argument call & dispatch therequestData action-creator with that argument as follows:

store.dispatch(requestData(42))

Or inreact-redux'connectmapDispatchToProps callback:

exportdefaultconnect(null,{ requestData})(Component)

Selecting theCommunication for a given request from your store-state

The second element in the tuple returned fromcreateRequest is aselector that returns theCommunication object for the created request.

import{createRequest}from'redux-communication'constdataRequest=createRequest('data',()=>fetch(endpoint),)const[,dataCommunicationSelector]=dataRequest

Use it to retrieve the the communication-state for the associated request.

constdataCommunication=dataCommunicationSelector(store.getState())const{ fetching, error, response}=dataCommunication

Or inreact-redux'connectmapStateToProps callback:

constmapStateToProps=state=>({dataCommunication:dataCommunicationSelector(state)})exportdefaultconnect(mapStateToProps)(Component)

Imperatively handling request success/error with Promise chaining

If having only theCommunication object available to you via thecommunicationSelector is not enough to handle a particular request and you would prefer to trigger some imperative action either or completion or failure of any given request you can do so by hooking into the promise returned from the call to dispatch:

constdataRequest=createRequest('data',()=>fetch(endpoint),)const[requestData]=dataRequeststore.dispatch(requestData()).then(/* handle success imperatively */).catch(/* handle error imperatively */)

Or from inside a react-component (assuming dispatch-wrapped action-creator injected throughreact-redux-connect props):

componentDidMount(){this.props.requestData().then(/* handle success imperatively */).catch(/* handle error imperatively */)}

Listening for request-actions yourself

The third element in the tuple returned fromcreateRequest is aRequestActionTypes object for the created request.You can use it to hook your own reducers up to the events of that request's communication-state.

import{createRequest}from'redux-communication'constdataRequest=createRequest('data',()=>fetch(endpoint),)const[,,dataRequestActionTypes]=dataRequestconstdataReducer=(state,action)=>{switch(action.type){casedataRequestActionTypes.succeeded:{const{ response}=action.payload/*       * react to the data-request having succeeded you       * have access to action.payload.response here       *       * response being the value your promise resolved with       */}}}

API

createCommunication:

() => [  requestMiddleware,  requestReducer,]

Should be self-explanatory, seeInstallation guide for usage of this.


createRequest:

(namespace, request) => [  requestActionCreator,  requestCommunicationSelector,  requestActionTypes,]

namespace: string

Used to create name-spaced action-types of this format@@communication [ namespace ] REQUESTED

request: (...args) => Promise

Returns a promise

will receive whatever you pass into the action-creator returned fromcreateRequest

requestActionCreator: (...args) => Action

Action-Creator

returns a redux-action

the arguments you pass into this are passed to therequest function (2nd argument ofcreateRequest)

Redux Docs: Action Creators

requestCommunicationSelector: (state) => Communication

Selector function, returns aCommunication object

Redux Docs: Selectors

requestActionTypes: RequestActionTypes

RequestActionTypes


RequestActionTypes:

{  requested: string  failed: string  succeeded: string}

The action-types a given request uses to track its communication-state.


Communication:

{  fetching: boolean  error: any  response: any}

fetching: boolean

The fetching state of a given request-communication

error: any

The error your promise might throw (the promise that is returned from therequest argument increateRequest)

response: any

The value your promise might resolve to (the promise that is returned from therequest argument increateRequest)


Does this cover my use case?

This library is agnostic as can be about any other aspect of your application in order to cover as many edge-cases as possible.

It does for example not make assumptions about the technology you are using to make your requests ( can beaxios, can befetch, can even bejQ ).

Because your use-case might not be covered by simply storing the error/response in some place in the state this library exposes the generated action-types created for each request so you can hook into them.

Nothing is hidden away, everything passing through the communication-middleware is exposed and you can listen for it too!


License

MIT @ Matthias Margotmatthiasmargot@hotmail.com

About

Request communication-state tracker, pluggable into redux.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp