Skip to content

Instantly share code, notes, and snippets.

@Calvin-Huang
Last active October 1, 2020 12:44
Show Gist options
  • Save Calvin-Huang/c7600e191be7c8bccb43000ec3694724 to your computer and use it in GitHub Desktop.
Save Calvin-Huang/c7600e191be7c8bccb43000ec3694724 to your computer and use it in GitHub Desktop.
The most simple and common implementation for login and request user's data with credential.
/* /page/home.jsx */
import { useState, useEffect } from 'react'
import axios from '@util/axios'
const Home = () => {
const [user, setUser] = useState({})
useEffect(async () => {
const { data } = await axios.get('https://mock.bugfree.app/api/me')
setUser(data)
})
return (
<h1>{user.name}</h1>
)
}
export default Home
------
/* /util/axios.js */
import Cookies from './cookie'
import originalAxios from 'axios'
export const axios = originalAxios.create()
// Customized axios with interceptor to add Authorization content to header for every requests.
axios.interceptors.request.use(config => {
config.headers = {
authorization: `Bearer ${Cookies.shared.get('user-token')}`,
...config.headers,
}
return config
})
export default axios
------
/* /util/cookie.js */
import Cookies from 'universal-cookie'
export const cookie = {
new(cookieString) {
return new Cookies(cookieString)
},
set shared(value) {
this._cookie = value
},
get shared() {
if (!this._cookie) {
this._cookie = new Cookies()
}
return this._cookie
},
}
export default cookie
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment