I have in my parent component App.js
a Header
and a Footer
.
I want to switch the components between the Header
and Footer
by clicking buttons inside the two of them.
Each time the pageIndex
changed I want to replace to some other component.
I'm getting this error Cannot read property 'push' of undefined
Why am I getting this error and is that a clean and proper whey to do it (with my defaultRouter()
and useMemo
) ?
function App() {
const [pageIndex, setPageIndex] = useState();
const [searchResults, setSearchResults] = useState([]);
const history = useHistory();
useEffect(() => {
console.log(pageIndex, 'App');
}, [pageIndex]);
const defaultRouter = useMemo(() => {
// Or - `const DefaultRouter = useMemo(() =>` instead of `useEffect()`
switch (pageIndex) {
case 1:
history.push({ pathname: '/search', state: searchResults });
break;
case 2:
history.push('/cart');
break;
default:
history.push('/');
break;
}
}, [pageIndex]);
return (
<div className='App'>
<Header/>
<Home />
{defaultRouter};
<Footer />
<BrowserRouter>
<Route path='/'>
<Home />
</Route>
<Route path='/search'>
<Search
searchResults={searchResults}
setItemsAmount={setItemsAmount}
/>
</Route>
<Route path='/cart'>
<Cart />
</Route>
<Route component={PageNotFound} />
</BrowserRouter>
;
</div>
);
}
Edit
As Shyam adviced in his answer below, I changed my App.js
with useCallback
but useCallback
just doesn't work.
const defaultRouter = useCallback(() => {
console.log(pageIndex, 'callBack');
switch (pageIndex) {
case 1:
history.push({ pathname: '/search', state: searchResults });
break;
case 2:
history.push('/cart');
break;
default:
history.push('/');
break;
}
}, [pageIndex]);
Thanks