Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ node_modules/
npm-debug.log
yarn-error.log
dist/
coverage/
coverage/
.history/
.github/
39 changes: 33 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,13 +154,15 @@ applyAuthTokenInterceptor(axiosInstance, {
## Non-TypeScript implementation

```javascript
//api.js

import { applyAuthTokenInterceptor } from 'react-native-axios-jwt';
import axios from 'axios';

const BASE_URL = 'https://api.example.com'

// 1. Create an axios instance that you wish to apply the interceptor to
const axiosInstance = axios.create({ baseURL: BASE_URL })
export const axiosInstance = axios.create({ baseURL: BASE_URL })

// 2. Define token refresh function.
const requestRefresh = async (refresh) => {
Expand All @@ -172,21 +174,46 @@ const requestRefresh = async (refresh) => {

// 3. Apply interceptor
// Notice that this uses the axiosInstance instance.
applyAuthTokenInterceptor(axiosInstance, { requestRefresh });
applyAuthTokenInterceptor(axiosInstance, { requestRefresh });
```
### Login/logout

```javascript
//login.js

// 4. Logging in
import {
isLoggedIn,
setAuthTokens,
clearAuthTokens,
getAccessToken,
getRefreshToken,
} from 'react-native-axios-jwt';
import { axiosInstance } from '../api';

// 4. Log in by POST-ing the email and password and get tokens in return
// and call setAuthTokens with the result.
const login = async (params) => {
const response = await axiosInstance.post('/auth/login', params)

// save tokens to storage
await setAuthTokens({
await setAuthTokens({
accessToken: response.data.access_token,
refreshToken: response.data.refresh_token
})
}

// 5. Logging out
const logout = async () => await clearAuthTokens()
// 5. Log out by clearing the auth tokens from AsyncStorage
const logout = () => clearAuthTokens()

// Check if refresh token exists
if (isLoggedIn()) {
// assume we are logged in because we have a refresh token
}

// Get access to tokens
const accessToken = getAccessToken().then(accessToken => console.log(accessToken))
const refreshToken = getRefreshToken().then(refreshToken => console.log(refreshToken))


// Now just make all requests using your axiosInstance instance
axiosInstance.get('/api/endpoint/that/requires/login').then(response => { })
Expand Down