npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

redux-devise-axios-native

v0.0.1

Published

Redux Middleware to help set axios headers when using Devise Token Auth

Downloads

8

Readme

About

This package fits a very specific use case. It's purpose is to keep help keep track of new tokens everytime a request is made. It works by capturing the dispatch and updating the axios config with the new headers recieved from devise. There is also a validate token option as well as a logout option.

  • You are using devise token authentiation
  • You are using axios
  • You are using redux
  • You are using React Native

Installation

npm install redux-devise-axios-native

store.js

import { createStore, compose, applyMiddleware } from 'redux';

//This could be saga or promise or any other async middleware
import thunk from 'redux-thunk';

import apiMiddleware from 'redux-devise-axios-native';

import rootReducer from './reducers/index';
import axios from 'axios';


/* OPTIONS
  axios: Your axios instance *required
  customHeaders: An array of headers you want to add.  Defaults: ['access-token', 'token-type', 'client', 'expiry', 'uid']
  validateAction: default 'VALIDATE_TOKEN'
  logoutAction: default 'LOGOUT'
*/
const options = { axios }


//redux-devise-axios middleware must come after your async middleware
const enhancers = compose(
  applyMiddleware(thunk, apiMiddleware(options)),
  window.devToolsExtension ? window.devToolsExtension() : f => f
);

const store = createStore(rootReducer, {}, enhancers);

Options

  • axios: This is your instance of axios and is required
  • customHeaders: Array of additional Headers you want to use
    • default: ['access-token', 'token-type', 'client', 'expiry', 'uid'] This is what devise sends by default
  • validateAction: This is the action you dispatch in an HOC (Usually because the user refreshed the browser)
    • default: 'VALIDATE_TOKEN'
  • logoutAction: This is the action you dispatch to logout your user.
    • default: 'LOGOUT'

NOTE: You are resposible for the implementation of LOGOUT and VALIDATE token. These actions simply add to and clear localStorage.

Example Usage

actions/auth.js

import axios from 'axios';
import { setFlash } from '../actions/flash';

export const registerUser = (email, password, passwordConfirmation, history) => {
  return(dispatch) => {
    axios.post('/api/auth', { email, password, password_confirmation: passwordConfirmation })
      .then( res => {
        let { data: { data: user }, headers } = res;
        dispatch({ type: 'LOGIN', user, headers });
        history.push('/');
      })
      .catch( res => {
        const message = res.response.data.errors.full_messages.join(',');
        dispatch(setFlash(message, 'error'));
    });
  }
}

export const handleLogout = (history) => {
  return(dispatch) => {
    axios.delete('/api/auth/sign_out')
      .then( res => {
        dispatch({ type: 'LOGOUT' });
        dispatch(setFlash('Logged out successfully!', 'success'));
        history.push('/login');
      })
      .catch( res => {
        // TODO: handle errors for the client
        console.log(res);
      });
    }
}

export const handleLogin = (email, password, history) => {
  return(dispatch) => {
    axios.post('/api/auth/sign_in', { email, password })
      .then( res => {
        let { data: { data: user }, headers } = res
        dispatch({ type: 'LOGIN', user, headers });
        history.push('/');
      })
      .catch( res => {
        // TODO: handle errors for the client
        console.log(res);
      })
  }
}

export const validateToken = (cb = f => f) => {
  return (dispatch) => {
    dispatch({ type: 'VALIDATE_TOKEN' })
    let headers = axios.defaults.headers.common
    axios.get('/api/auth/validate_token', headers)
      .then( res => dispatch({ type: 'LOGIN', user: res.data.data }) )
      .catch(() => cb())
  }
}

Notice that we are sending the headers when we dispatch. This is key to how this package works. Anytime any action is dispatched with a key of headers axios headers will be updated.

This will work for React State as well as long as you dispatch some action with the res.headers from axios.

  componentDidMount() {
    axios.get('/api/bio')
      .then( res => {
        this.setState({ bio: res.data.body });
        this.props.dispatch(setHeaders(res.headers))
      })
      .catch( res => {
        console.log(`Bio GET Fail: ${res}`);
      });
  }