Skip to content

Commit

Permalink
Merge pull request #20 from ko-lem/master
Browse files Browse the repository at this point in the history
Fix useApi to not return a new axios instance every render
  • Loading branch information
ctrlaltdylan committed Sep 1, 2022
2 parents 6f6d486 + 9f8d136 commit 0ff540f
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions src/hooks/useApi.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,32 @@
import { useContext } from "react";
import { useContext, useEffect } from "react";
import axios from "axios";
import { getSessionToken } from "@shopify/app-bridge-utils";
import { Context as ShopifyAppContext } from "@shopify/app-bridge-react";

const api = axios.create();

/**
* Creates a axios client that uses Shopify JWT Session Token authentication
*
* @returns axios
*/
export default function useApi() {
const api = axios.create();
const app = useContext(ShopifyAppContext);

api.interceptors.request.use((config) => {
return getSessionToken(app)
.then((token) => {
config.headers["Authorization"] = `Bearer ${token}`;
return config;
})
.catch((err) => {
console.log(err);
useEffect(() => {
if (app) {
api.interceptors.request.use((config) => {
return getSessionToken(app)
.then((token) => {
config.headers["Authorization"] = `Bearer ${token}`;
return config;
})
.catch((err) => {
console.log(err);
});
});
});
}
}, [app]);

return api;
}

0 comments on commit 0ff540f

Please sign in to comment.