Skip to content

Instantly share code, notes, and snippets.

@YuriFontella
Last active January 18, 2021 21:24
Show Gist options
  • Select an option

  • Save YuriFontella/4c7925edd3e6fb47d684ffd95bff556d to your computer and use it in GitHub Desktop.

Select an option

Save YuriFontella/4c7925edd3e6fb47d684ffd95bff556d to your computer and use it in GitHub Desktop.
hook api requests react (axios, swr)
import { getSession } from 'next-auth/client'
import { useCallback, useState } from 'react'
import axios from 'axios'
import useSWR, { mutate } from 'swr'
const api = axios.create({
baseURL: process.env.API,
timeout: 8000,
withCredentials: true
})
api.interceptors.request.use(async function(config) {
const session = await getSession()
if (session)
config.headers['x-access-token'] = session.access_token
return config
})
const http = () => {
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const request = useCallback(async (url, options) => {
let response
setError(null)
try {
setLoading(true)
response = await api(url, options)
} catch (error) {
setError(error)
} finally {
setLoading(false)
}
return response
}, [])
return { loading, error, request }
}
const swr = (key, options) => {
const { data, mutate, error } = useSWR(key, () => api(options).then(response => response.data))
return {
data: data,
loading: !error && !data,
error: error,
mutate
}
}
module.exports = { http, swr, mutate, api }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment