Skip to content

jlcastillo/redux-api-action

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

39 Commits
 
 
 
 
 
 

Repository files navigation

redux-api-action

Send HTTP requests to an API server, automatically dispatching actions with the result.

How it works

npm install redux-api-action --save

actions.js

import { createApiAction } from 'redux-api-action'
export const apiAuth = createApiAction('https://your.api.server.com', 'POST', '/api/auth')

component.js

Arguments to the api action wil be sent in the body of the HTTP request.

import { apiAuth } from 'actions'

const options = {body: {user: 'foo', password: 'oof'};

const SubmitComponent = ({ apiAuth }) =>
    <button onClick={() => apiAuth(options)}>
        Submit
    </button>

export default connect(null, { apiAuth })(SubmitComponent)

where options may contain:

  • body: the object that will be embedded in the body of the HTTP request
  • params: to replace strings in the URL. I.e. in a url like https://your.server.com/user/:id, you may replace :id using options = { params: {id: "1234"}}.
  • query: to add query arguments to the end of the URL. I.e. to add ?name=jose&surname=castillo to the end of an URL, you would use options = {query: {name: "jose", surname="castillo"} }

reducers.js

import { apiAuth } from 'actions'

export default (state = [], { type, payload, meta, error }) => {
  switch(type) {
    case apiAuth.types.request: {
        if(error)
            // API call timed out
        else
            // API call just sent, response not received yet
    }
    case apiAuth.types.success: {
      // API call succeeded, response comes in 'payload'
    }
    case apiAuth.types.failure: {
        // API answered with an error, status in 'payload.status'
    }
    default:
      return state;
  }
}

where:

  • type = "[POST]/api/auth"
  • meta = {body: {user: 'foo', password: 'oof'}} (the options passed to apiAuth)
  • error = true if there was an error, undefined otherwise.
  • if success:
    • payload = { token: 12332432543 }
  • if error:
    • payload.status = 404 (an error code)

Prerequisites

redux-api-action relies on redux-api-middleware and redux-thunk:

npm install redux-api-middleware redux-thunk --save

configureStore.js

import { createStore, applyMiddleware, combineReducers } from 'redux';
import { apiMiddleware } from 'redux-api-middleware';
import thunk from 'redux-thunk';
import reducers from './reducers';

const reducer = combineReducers({...reducers, api: (state=null, action) => state});
const createStoreWithMiddleware = applyMiddleware(thunk, apiMiddleware)(createStore);

export default function configureStore(initialState) {
  return createStoreWithMiddleware(reducer, initialState);
}

Authentication

If the redux store contains a token at auth.token, all HTTP requests will be sent with the header 'Authorization' = 'Bearer '+ auth.token.

Query Strings

To POST to an endpoint using /api/auth?jwt=true

// declare the API
export const apiAuth = createApiAction('https://your.api.server.com', 'POST', '/api/auth')
...
// dispatch it (assumming you wrapped it in mapDispatchToProps)
apiAuth({query: {jwt: true}, body: {user: 'foo', password: 'oof'}})

Interpolated Params

To POST to an endpoint using /api/:id/auth

// declare the API
export const apiAuth = createApiAction('https://your.api.server.com', 'POST', '/api/:id/auth')
...
// dispatch it (assumming you wrapped it in mapDispatchToProps)
apiAuth({params: {id: '1234'}, body: {user: 'foo', password: 'oof'}})

Callbacks

Usually you will connect to the redux store to get data retrieved from the API, but there may be situations where you need to run some tasks as a result of an API call and you don't want to mess with redux. You can provide onSuccess and/or onError callbacks as options:

// declare the API
export const apiAuth = createApiAction('https://your.api.server.com', 'POST', '/api/:id/auth')
...
// dispatch it (assumming you wrapped it in mapDispatchToProps)
apiAuth({body: {user: 'foo', password: 'oof'}}, onSuccess: (resp) => console.log(resp), onError: (resp) => console.error(resp))

Authors

  • Jose Luis Castillo - Initial work

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Acknowledgments

  • the authors of redux-api-middleware for their great library

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •