Get AdSense Ads to Reload on Route Change in Next JS - reactjs

We've implemented Google AdSense on our Next.JS website, but we'd like to have ads reload whenever the route changes.
Here is what I tried:
const AdBlock = props => {
const { userLoaded, currentUserIsSilverPlus } = useAuth()
useEffect(() => {
window.adsbygoogle = window.adsbygoogle || []
window.adsbygoogle.push({})
}, [])
const reloadAds = () => {
const { googletag } = window
if (googletag) {
googletag.cmd.push(function () {
googletag.pubads().refresh()
})
}
}
Router.events.on("routeChangeStart", reloadAds)
if (userLoaded && !currentUserIsSilverPlus) {
return (
<ins
className="adsbygoogle adbanner-customize"
style={{ display: "block" }}
data-ad-client="ca-pub-1702181491157560"
data-ad-slot={props.slot}
data-ad-format={props.format}
data-full-width-responsive={props.responsive}
/>
)
}
return ""
}
export default AdBlock
The ads load, however, they never appear to refresh. What am I missing?

My solution was to observe router event changes, when routeChangeStart ads had to be unmounted, when routeChangeComplete they had to be mounted remounted.
// components/Adsense.tsx
function Ads() {
const adsRef = useRef<HTMLModElement | null>(null);
useEffect(() => {
const executeWindowAds = () => {
try {
// #ts-ignore
(adsbygoogle = window.adsbygoogle || []).push({});
} catch (error: any) {
console.error('error ads======>', error.message);
}
};
const insHasChildren = adsRef.current?.childNodes.length;
if (!insHasChildren) {
executeWindowAds();
}
}, []);
return (
<ins
ref={adsRef}
className="adsbygoogle"
style={{ display: 'block' }}
data-ad-client="ca-pub-xxx"
data-ad-slot="xxx"
data-ad-format="auto"
data-full-width-responsive="true"
></ins>
);
}
export default function Adsense() {
const router = useRouter();
const [shouldMount, setShouldMount] = useState(true);
useEffect(() => {
const onRouteChangeStart = () => setShouldMount(false);
const onRouteChangeComplete = () => setShouldMount(true);
router.events.on('routeChangeStart', onRouteChangeStart);
router.events.on('routeChangeComplete', onRouteChangeComplete);
return () => {
router.events.off('routeChangeStart', onRouteChangeStart);
router.events.off('routeChangeComplete', onRouteChangeComplete);
};
}, [router.events]);
return shouldMount ? <Ads /> : null;
}
On your layout page, for example a sidebar where each page has the same sidebar:
// components/LayoutBlogPost.tsx
import dynamic from 'next/dynamic';
const Adsense = dynamic(() => import('./Adsense'), { ssr: false });
export default function LayoutBlogPost({children}: {children: any}) {
return (
<div>
{children}
<Adsense />
</div>
);
}

try useRouter hook and handling router events inside useEffect:
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter();
useEffect(() => {
router.events.on('routeChangeError', handleChange)
}, [])
return (
<>
</>
)
}

Related

Need to call an alert message component from action in react

I've created a common component and exported it, i need to call that component in action based on the result from API. If the api success that alert message component will call with a message as "updated successfully". error then show with an error message.
calling service method in action. is there any way we can do like this? is it possible to call a component in action
You have many options.
1. Redux
If you are a fan of Redux, or your project already use Redux, you might want to do it like this.
First declare the slice, provider and hook
const CommonAlertSlice = createSlice({
name: 'CommonAlert',
initialState : {
error: undefined
},
reducers: {
setError(state, action: PayloadAction<string>) {
state.error = action.payload;
},
clearError(state) {
state.error = undefined;
},
}
});
export const CommonAlertProvider: React.FC = ({children}) => {
const error = useSelector(state => state['CommonAlert'].error);
const dispatch = useDispatch();
return <>
<MyAlert
visible={error !== undefined}
body={error} onDismiss={() =>
dispatch(CommonAlertSlice.actions.clearError())} />
{children}
</>
}
export const useCommonAlert = () => {
const dispatch = useDispatch();
return {
setError: (error: string) => dispatch(CommonAlertSlice.actions.setError(error)),
}
}
And then use it like this.
const App: React.FC = () => {
return <CommonAlertProvider>
<YourComponent />
</CommonAlertProvider>
}
const YourComponent: React.FC = () => {
const { setError } = useCommonAlert();
useEffect(() => {
callYourApi()
.then(...)
.catch(err => {
setError(err.message);
});
});
return <> ... </>
}
2. React Context
If you like the built-in React Context, you can make it more simpler like this.
const CommonAlertContext = createContext({
setError: (error: string) => {}
});
export const CommonAlertProvider: React.FC = ({children}) => {
const [error, setError] = useState<string>();
return <CommonAlertContext.Provider value={{
setError
}}>
<MyAlert
visible={error !== undefined}
body={error} onDismiss={() => setError(undefined)} />
{children}
</CommonAlertContext.Provider>
}
export const useCommonAlert = () => useContext(CommonAlertContext);
And then use it the exact same way as in the Redux example.
3. A Hook Providing a Render Method
This option is the simplest.
export const useAlert = () => {
const [error, setError] = useState<string>();
return {
setError,
renderAlert: () => {
return <MyAlert
visible={error !== undefined}
body={error} onDismiss={() => setError(undefined)} />
}
}
}
Use it.
const YourComponent: React.FC = () => {
const { setError, renderAlert } = useAlert();
useEffect(() => {
callYourApi()
.then(...)
.catch(err => {
setError(err.message);
});
});
return <>
{renderAlert()}
...
</>
}
I saw the similar solution in Antd library, it was implemented like that
codesandbox link
App.js
import "./styles.css";
import alert from "./alert";
export default function App() {
const handleClick = () => {
alert();
};
return (
<div className="App">
<button onClick={handleClick}>Show alert</button>
</div>
);
}
alert function
import ReactDOM from "react-dom";
import { rootElement } from ".";
import Modal from "./Modal";
export default function alert() {
const modalEl = document.createElement("div");
rootElement.appendChild(modalEl);
function destroy() {
rootElement.removeChild(modalEl);
}
function render() {
ReactDOM.render(<Modal destroy={destroy} />, modalEl);
}
render();
}
Your modal component
import { useEffect } from "react";
export default function Modal({ destroy }) {
useEffect(() => {
return () => {
destroy();
};
}, [destroy]);
return (
<div>
Your alert <button onClick={destroy}>Close</button>
</div>
);
}
You can't call a Component in action, but you can use state for call a Component in render, using conditional rendering or state of Alert Component such as isShow.

socket.on State Not Changing while sending socket.emit() in a map React

I'm using socket.io along with react for a project. Here's my component
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { io } from 'socket.io-client';
import Button from '../../components/Button';
import { IProject } from '../../interfaces/projects';
import { IRun } from '../../interfaces/runs';
const socket = io(process.env.REACT_APP_SERVER_URL);
export default function RunAll() {
const { search } = useLocation();
// API State
const [project, setProject] = useState<IProject | undefined>(undefined);
const [runs, setRuns] = useState<IRun[]>([]);
// Query Params
const queryParams = new URLSearchParams(search);
const projectId = queryParams.get('projectId')!;
// Get Project
useEffect(() => {
(async () => {
const { data: project } = await axios.get(`${process.env.REACT_APP_SERVER_URL}/api/projects/${projectId}`);
setProject(project.data);
})();
}, [projectId]);
// Clear socket
useEffect(() => () => {
socket.close();
});
const runAllTests = async () => {
project?.tests.forEach((test) => {
console.log(test);
socket.emit('create run', { projectId, testId: test.id, url: process.env.REACT_APP_SERVER_URL });
});
socket.on('created run', (run: IRun) => {
console.log(run);
setRuns([...runs, run]);
});
};
console.log(runs);
const renderHeader = () => (
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', alignItems: 'center' }} className='mb-3'>
<h1 className='heading-primary mt-auto mb-auto'>Run Overview</h1>
<Button onClick={runAllTests}>Run All Tests</Button>
</div>
);
return (
<main>
{renderHeader()}
{runs?.map((run) => (
<div>{run.id}</div>
))}
</main>
);
}
When the button is click and runAllTests() is called, i can see the console.log(test) in the console and my server logs also show me that it has received the socket.emit('create run'). And when the server responds with socket.on('created run'), I can see the value of the created run. However, only the 2nd run(in case of the length of project.tests being 2), only the last run is being added to the state.
What am I missing here? Please help me out! Thanks in advance!
socket.on('created run', (run: IRun) => { console.log(run); setRuns([...runs, run]); });
use this code in useEffect and make sure it only runs once. Following should work for you.
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { io } from 'socket.io-client';
import Button from '../../components/Button';
import { IProject } from '../../interfaces/projects';
import { IRun } from '../../interfaces/runs';
const socket = io(process.env.REACT_APP_SERVER_URL);
export default function RunAll() {
const { search } = useLocation();
// API State
const [project, setProject] = useState<IProject | undefined>(undefined);
const [runs, setRuns] = useState<IRun[]>([]);
// Query Params
const queryParams = new URLSearchParams(search);
const projectId = queryParams.get('projectId')!;
// Get Project
useEffect(() => {
(async () => {
const { data: project } = await axios.get(`${process.env.REACT_APP_SERVER_URL}/api/projects/${projectId}`);
setProject(project.data);
})();
}, [projectId]);
// Clear socket
useEffect(() => () => {
socket.on('created run', (run: IRun) => {
console.log(run);
setRuns([...runs, run]);
});
return function cleanup () {
socket.close();
}
},[]);
const runAllTests = async () => {
project?.tests.forEach((test) => {
console.log(test);
socket.emit('create run', { projectId, testId: test.id, url: process.env.REACT_APP_SERVER_URL });
});
};
console.log(runs);
const renderHeader = () => (
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', alignItems: 'center' }} className='mb-3'>
<h1 className='heading-primary mt-auto mb-auto'>Run Overview</h1>
<Button onClick={runAllTests}>Run All Tests</Button>
</div>
);
return (
<main>
{renderHeader()}
{runs?.map((run) => (
<div>{run.id}</div>
))}
</main>
);
}

How to prevent UI flickering while conditionally rendering components?

Consider the following code:
const Home = () => {
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(authUser => {
if(authUser) {
setUser(authUser);
} else {
setUser(null)
}
});
return () => unsubscribe();
}, []);
return (
<div>
{user ? (
<Hero />
) : (
<Login />
)}
</div>
)
}
export default Home
The Login component has all the functions which handles all the Sign Up, Login and Third-Party Authentications using Firebase.
The problems are:
When I reload the page and if the user is already logged in, it shows the component for some time, and then renders the component, which gives a bad UX.
Also, when I sign in using Google or Facebook, again this component is rendered before finally rendering the component.
Please throw some light into this issue. Your help will be highly appreciated!
Edit:
Problem 1 is solved, but problem 2 is not. Here is the relevant code for problem 2:
Login.js
<div style={{ marginBottom: "2%" }}>
<GoogleSignup />
</div>
GoogleSignup.js
import { GoogleLoginButton } from "react-social-login-buttons";
import firebase from "firebase";
import fire from "../fire";
const GoogleSignup = ({ extensionId }) => {
const OnSubmitButton = async () => {
var provider = new firebase.auth.GoogleAuthProvider();
fire
.auth()
.signInWithPopup(provider)
.then((result) => {
const credential = result.credential;
const token = credential.accessToken;
const user = result.user;
})
.catch((error) => {
console.log(error);
});
};
return (
<div>
<GoogleLoginButton
style={{ fontSize: "17px" }}
text={"Continue with Google"}
align={"center"}
onClick={OnSubmitButton}
/>
</div>
);
};
export default GoogleSignup;
These lines:
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(authUser => {
if(authUser) {
setUser(authUser);
} else {
setUser(null)
}
});
return () => unsubscribe();
}, []);
can be replaced with just:
useEffect(() => auth.onAuthStateChanged(setUser), []);
Next, instead of passing in just null to the useState, pass in current user.
const [user, setUser] = useState(null);
becomes
const [user, setUser] = useState(auth.currentUser);
This results in:
const Home = () => {
const [user, setUser] = useState(auth.currentUser);
useEffect(() => auth.onAuthStateChanged(setUser), []);
return (
<div>
{user ? (
<Hero />
) : (
<Login />
)}
</div>
)
}
export default Home
Personally, I tend to use undefined/null/firebase.auth.User using:
const Home = () => {
const [user, setUser] = useState(() => firebase.auth().currentUser || undefined);
const loadingUser = user === undefined;
useEffect(() => firebase.auth().onAuthStateChanged(setUser), []);
if (loadingUser)
return null; // or show loading icon, etc.
return (
<div>
{user ? (
<Hero />
) : (
<Login />
)}
</div>
)
}
export default Home
After the popup has closed, Firebase Authentication still needs to handle the authentication flow of exchanging the provider's authentication token for a Firebase User token. While this is taking place, you should show some form of loading screen in your component. In the below code sample, I change the "Continue with Google" text to "Signing in..." and disable the onClick events for each button while the sign in process takes place.
import { GoogleLoginButton } from "react-social-login-buttons";
import firebase from "firebase";
import fire from "../fire";
const PROVIDER_ID_GOOGLE = firebase.auth.GoogleAuthProvider.PROVIDER_ID;
const ignoreOnClick = () => {};
const GoogleSignup = ({ extensionId }) => {
const [activeSignInMethod, setActiveSignInMethod] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
if (activeSignInMethod === null)
return; // do nothing.
let disposed = false, provider;
switch (activeSignInMethod) {
case PROVIDER_ID_GOOGLE:
provider = new firebase.auth.GoogleAuthProvider();
break;
default:
// this is here to help catch when you've added a button
// but forgot to add the provider as a case above
setError("Unsupported authentication provider");
return;
}
fire.auth()
.signInWithPopup(provider)
.then((result) => {
// const credential = result.credential;
// const token = credential.accessToken;
// const user = result.user;
if (!disposed) {
setError(null);
setActiveSignInMethod(null);
}
})
.catch((error) => {
console.error(`Failed to sign in using ${activeSignInMethod}`, error);
if (!disposed) {
setError("Failed to sign in!");
setActiveSignInMethod(null);
}
});
return () => disposed = true; // <- this is to prevent any "updating destroyed component" errors
}, [activeSignInMethod]);
return (
{ error && (<div key="error">{error}</div>) }
<div key="signin-list">
<GoogleLoginButton
style={{ fontSize: "17px" }}
text={
activeSignInMethod == PROVIDER_ID_GOOGLE
? "Signing in..."
: "Continue with Google"
}
align={"center"}
onClick={
activeSignInMethod === null
? () => setActiveSignInMethod(PROVIDER_ID_GOOGLE)
: ignoreOnClick
}
/>
</div>
);
};
export default GoogleSignup;

React useState hook is not working as expected inside useEffect hook

Disclaimer: Please don't mark this as duplicate. I've seen similar questions with answers. But none of them is working for me. I'm just learning React.
What I'm trying to achieve is basically infinite scrolling. So that when a user scrolls to the end of the page, more data will load.
I've used scroll eventListener to achieve this. And it is working.
But I'm facing problems with the state of the variables.
First, I've changed the loading state to true. Then fetch data and set the state to false.
Second, when scrolling to the end of the page occurs, I again change the loading state to true. Add 1 with pageNo. Then again fetch data and set the loading state to false.
The problems are:
loading state somehow remains true.
Changing the pageNo state is not working. pageNo always remains to 1.
And actually none of the states are working as expected.
My goal: (Sequential)
Set loading to true.
Fetch 10 posts from API after component initialization.
Set loading to false.
After the user scrolls end of the page, add 1 with pageNo.
Repeat Step 1 to Step 3 until all posts loaded.
After getting an empty response from API set allPostsLoaded to true.
What I've tried:
I've tried adding all the states into dependencyList array of useEffect hook. But then an infinite loop occurs.
I've also tried adding only pageNo and loading state to the array, but same infinite loop occurs.
Source:
import React, { lazy, useState } from 'react';
import { PostSection } from './Home.styles';
import { BlogPost } from '../../models/BlogPost';
import { PostService } from '../../services/PostService';
const defaultPosts: BlogPost[] = [{
Id: 'asdfg',
Content: 'Hi, this is demo content',
Title: 'Demo title',
sections: [],
subTitle: '',
ReadTime: 1,
CreatedDate: new Date()
}];
const defaultPageNo = 1;
const PostCardComponent = lazy(() => import('./../PostCard/PostCard'));
const postService = new PostService();
const Home = (props: any) => {
const [posts, setPosts]: [BlogPost[], (posts: BlogPost[]) => void] = useState(defaultPosts);
const [pageNo, setPageNo] = useState(defaultPageNo);
const [pageSize, setPageSize] = useState(10);
const [loading, setLoading] = useState(false);
const [allPostsLoaded, setAllPostsLoaded] = useState(false);
const [featuredPost, setFeaturedPost]: [BlogPost, (featuredPost: BlogPost) => void] = useState(defaultPosts[0]);
async function getPosts() {
return await postService.getPosts(pageSize, pageNo);
}
async function getFeaturedPost() {
return await postService.getFeaturedPost();
}
function handleScroll(event: any) {
console.log('loading ' + loading);
console.log('allPostsLoaded ' + allPostsLoaded);
var target = event.target.scrollingElement;
if (!loading && !allPostsLoaded && target.scrollTop + target.clientHeight === target.scrollHeight) {
setLoading(true);
setPageNo(pageNo => pageNo + 1);
setTimeout(()=>{
getPosts()
.then(response => {
const newPosts = response.data.data;
setLoading(false);
if (newPosts.length) {
const temp = [ ...posts ];
newPosts.forEach(post => !temp.map(m => m.Id).includes(post.Id) ? temp.push(post) : null);
setPosts(temp);
} else {
setAllPostsLoaded(true);
}
})
}, 1000);
}
}
function init() {
setLoading(true);
Promise.all([getFeaturedPost(), getPosts()])
.then(
responses => {
setLoading(false);
setFeaturedPost(responses[0].data.data);
setPosts(responses[1].data.data);
}
);
}
React.useEffect(() => {
window.addEventListener("scroll", handleScroll);
init();
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []
);
return (
<PostSection className="px-3 py-5 p-md-5">
<div className="container">
<div className="item mb-5">
{posts.map(post => (
<PostCardComponent
key={post.Id}
Title={post.Title}
intro={post.Content}
Id={post.Id}
ReadTime={post.ReadTime}
CreatedDate={post.CreatedDate}
/>
))}
</div>
</div>
</PostSection>
);
};
export default Home;
Used more effects to handle the change of pageNo, loader and allPostsLoaded state worked for me.
Updated Source:
import React, { lazy, useState } from 'react';
import { Guid } from "guid-typescript";
import { PostSection } from './Home.styles';
import { BlogPost } from '../../models/BlogPost';
import { PostService } from '../../services/PostService';
import { Skeleton } from 'antd';
const defaultPosts: BlogPost[] = [{
Id: '456858568568568',
Content: 'Hi, this is demo content. There could have been much more content.',
Title: 'This is a demo title',
sections: [],
subTitle: '',
ReadTime: 1,
CreatedDate: new Date()
}];
const defaultPageNo = 1;
const defaultPageSize = 10;
const PostCardComponent = lazy(() => import('./../PostCard/PostCard'));
const postService = new PostService();
const Home: React.FC<any> = props => {
const [posts, setPosts]: [BlogPost[], (posts: BlogPost[]) => void] = useState(defaultPosts);
const [pageNo, setPageNo] = useState(defaultPageNo);
const [pageSize, setPageSize] = useState(defaultPageSize);
const [loading, setLoading] = useState(false);
const [allPostsLoaded, setAllPostsLoaded] = useState(false);
const [featuredPost, setFeaturedPost]: [BlogPost, (featuredPost: BlogPost) => void] = useState(defaultPosts[0]);
function getNewGuid() {
return Guid.create().toString();
}
async function getPosts() {
return await postService.getPosts(pageSize, pageNo);
}
async function getFeaturedPost() {
return await postService.getFeaturedPost();
}
function init() {
setLoading(true);
Promise.all([getFeaturedPost(), getPosts()])
.then(
responses => {
setLoading(false);
setFeaturedPost(responses[0].data.data);
setPosts(responses[1].data.data);
}
);
}
React.useEffect(() => {
init();
return;
}, []);
React.useEffect(() => {
if (allPostsLoaded || loading) return;
function handleScroll(event: any) {
var target = event.target.scrollingElement;
if (!loading && !allPostsLoaded && target.scrollTop + target.clientHeight === target.scrollHeight) {
setPageNo(pageNo => pageNo+1);
}
}
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, [loading, allPostsLoaded]
);
React.useEffect(() => {
if (pageNo > 1) {
setLoading(true);
setTimeout(()=>{
getPosts()
.then(response => {
const newPosts = response.data.data;
setTimeout(()=>{
setLoading(false);
if (newPosts.length) {
const temp = [ ...posts ];
newPosts.forEach(post => !temp.map(m => m.Id).includes(post.Id) ? temp.push(post) : null);
setPosts(temp);
} else {
setAllPostsLoaded(true);
}
}, 1000);
})
}, 1000);
}
}, [pageNo]
);
return (
<PostSection className="px-3 py-5 p-md-5">
<div className="container">
<div className="item mb-5">
{posts.map(post => (
<PostCardComponent
key={post.Id}
Title={post.Title}
intro={post.Content}
Id={post.Id}
ReadTime={post.ReadTime}
CreatedDate={post.CreatedDate}
/>
))}
</div>
</div>
</PostSection>
);
};
export default Home;

React HOC Using useEffect()

So i am using a HOC for general error handling purposes in react like this:
import React, { useState, useEffect } from 'react'
import Modal from '../../UI/Modal/Modal'
const WithErrorHandler = (WrappedComponent, axios) => {
const NewComponent = props => {
console.log('UseState')
const [error, setError] = useState(null)
console.log('runs')
useEffect(() => {
const req = axios.interceptors.request.use(config => {
console.log('request intercepted')
return config
})
const res = axios.interceptors.response.use(null, error => {
setError(error)
return Promise.reject(error)
})
return () => {
axios.interceptors.request.eject(req)
axios.interceptors.response.eject(res)
}
}, [])
return (
<div>
{console.log('render')}
{error ? (
<Modal clickHandler={() => setError(null)}> {error.message}</Modal>
) : null}
<WrappedComponent {...props} />
</div>
)
}
return NewComponent
}
export default WithErrorHandler
The problem i have run into is that i have a component which fires an axios request in it's useEffect().
When i try to wrap this component with my WithErrorHandler the useEffect of the wrapped component fires first then the useEffect of HOC withErrorHandler runs. This causes the axios request to be made faster than the HOC could register the axios interceptors. Any ideas on how to fix this would be aprreciated.
You can define an intermediate state which prevents from rendering wrapped component.
const WithErrorHandler = (WrappedComponent, axios) => {
const NewComponent = (props) => {
const [ready, setReady] = useState(false); // HERE
console.log("UseState");
const [error, setError] = useState(null);
console.log("runs");
useEffect(() => {
const req = axios.interceptors.request.use((config) => {
console.log("request intercepted");
return config;
});
const res = axios.interceptors.response.use(null, (error) => {
setError(error);
return Promise.reject(error);
});
setReady(true); // HERE
return () => {
axios.interceptors.request.eject(req);
axios.interceptors.response.eject(res);
};
}, []);
if (!ready) return null; // HERE
return (
<div>
{console.log("render")}
{error ? (
<Modal clickHandler={() => setError(null)}> {error.message}</Modal>
) : null}
<WrappedComponent {...props} />
</div>
);
};
return NewComponent;
};
What it does is that it makes sure that axios interceptor is initialized and it is good to render wrapped component.
Instead of if (!ready) return null; you can return a more sensible state from your HOC for instance, if (!ready) return <p>Initializing...</p>
You need an extra render for the NewComponent callback to run, adding a conditional rendering on WrappedComponent should do the trick.
Notice that we set isFirstRender on promise success, change it dependenly on your use case.
const WithErrorHandler = (WrappedComponent, axios) => {
const NewComponent = (props) => {
const [isFirstRender, setIsFirstRender] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
if (isFirstRender) {
const req = axios.interceptors.request.use((config) => {
return config;
});
// Check req success
if (req.isSuccess) { setIsFirstRender(false); }
const res = axios.interceptors.response.use(null, (error) => {
setError(error);
return Promise.reject(error);
});
return () => {
axios.interceptors.request.eject(req);
axios.interceptors.response.eject(res);
};
}
}, [isFirstRender]);
return (
<div>
{error ? (
<Modal clickHandler={() => setError(null)}> {error.message}</Modal>
) : null}
{!isFirstRender && <WrappedComponent {...props} />}
</div>
);
};
return NewComponent;
};

Resources