CacheRoute inside another Function Component
chitgoks opened this issue · comments
I commend this library because it saves a lot of new users from having to be forced to learn redux just to cater to this router issue.
My issue is because I created a functional component called ProtectedRoute where it returns the CacheRoute or a redirect if the user is not authenticated.
I place the ProtectedRoute tag in the CacheSwitch but it does not work. any idea what could be wrong with this code? Thank you
const ProtectedRoute = (props) => {
return localStorage.getItem('user') !== null
? <CacheRoute {...props} />
: <Redirect to="/login"/>;
};
export default ProtectedRoute;
And this is the cache switch
<CacheSwitch>
<ProtectedRoute component={MyComponent} path="/" exact/>
</CacheSwitch>
Hi~
Nothing wrong with your code, just because CacheSwitch
only saves the first layer of nodes which type is CacheRoute
by default.
Can config that behavior using which
prop on CacheSwitch
For your code
<CacheSwitch which={element => element.type === ProtectedRoute}>
<ProtectedRoute component={MyComponent} path="/" exact/>
</CacheSwitch>
which
prop is a function that would receive a instance of React Component, return true/false
to decide if CacheSwitch
need to save it
This prop has not been mentioned in the documentation yet.
Sorry about that and thanks for using react-router-cache-route
!
thank you! this works.