In my React app, I use component to wrap the authentication required routes. As explained in this answer, I assigned userInfo
as a user
prop to each and every child as follows.
const RequireAuth = props => {
const [userInfo,setUserInfo] = useState([])
useEffect( () => {
Axios.get('/users/me').then(res => {
setUserInfo(res.data)
console.log(userInfo)
}).catch(e => {
console.log(e)
})
}
})
const childrenWithProps = React.Children.map(props.children, child =>
React.cloneElement(child, { user: userInfo })
);
return isAuth ? (
<div>
{childrenWithProps}
</div>
) :
(<ClipLoader
size={120}
color={"#123abc"}
loading={loading}
/>
)
};
export default withRouter(RequireAuth)
I wrap the auth required routes with RequireAuth
as follows in App.js
.
<RequireAuth>
<Route exact path="/courses" component={Courses}></Route>
<Route exact path="/courses/:courseId" component={Course}></Route>
</RequireAuth>
My question is: How can I access user
in Course
component?