Here is how solve it. Since I can use hook here I did use “app = useAppBridge()” and add JWT token to header and pass header to Axios instance. useFetchDataApiShopify is kind of single point to make api call. I was trying to use interceptor to add token to header but I was not able to use useAppBridge in the interceptor.
mport React from 'react';
import AxiosShopify from '../../AxiosShopify';
import { useAppBridge } from '@shopify/app-bridge-react';
import { getSessionToken } from '@shopify/app-bridge-utils';
const config = {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
};
/*
this is custom hook that fetch data from my backend
*/
export const useFetchDataApiShopify = (url) => {
const app = useAppBridge();
const [responseData, setResponseData] = React.useState(undefined);
const [isError, setIsError] = React.useState(undefined);
const [isLoading, setIsLoading] = React.useState(undefined);
React.useEffect(() => {
const fetchData = async (url) => {
setIsLoading(true);
try {
const token = await getSessionToken(app);
config.headers['Authorization'] = `Bearer ${token}`;
const result = await AxiosShopify.get(url, config);
setResponseData(await result.data);
console.log('set response fetch11', result);
setIsLoading(false);
} catch (error) {
// console.log('set response fetch error', error);
setIsError(error);
}
};
fetchData(url);
}, [url]);
return [responseData, isError, isLoading];
};
//*****Interceptor file became like this *******
mport React from 'react';
import axios from 'axios';
import { getSessionToken } from '@shopify/app-bridge-utils';
const AxiosShopify = axios.create();
AxiosShopify.interceptors.request.use(function (config) {
// return getSessionToken(window.app) // requires a Shopify App Bridge instance
// .then((token) => {
// // Append your request headers with an authenticated token
// config.headers['Authorization'] = `Bearer ${token}`;
// return config;
// });
return config;
});
// Export your Axios instance to use within your app
export default AxiosShopify;