I know this question has been asked many times before and I have tried the answers, but my problem still persists.
I am making a website using ReactJS, Redux with Firebase Authentication and Realtime DB.
I am trying to fetch displayName
and photoURL
using props from redux. These are the relevant codes.
index.js
const store = createStore(combinedReducers)
const IndexRoutes = (props) => {
useEffect(() => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
props.setUser(user)
props.history.push("/");
} else {
props.setUser(null)
props.history.push("/login");
}
})
}, []);
console.log(`user: ${props.currentUser}`)
return (
<Switch>
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<Route path='/' component={App} />
</Switch>
)
}
const mapStateToProps = (state) => {
return {
currentUser: state.user.currentUser
}
}
const mapDispatchToProps = (dispatch) => {
return {
setUser: (user) => {dispatch(setUser(user))}
}
}
const IndexRouter = withRouter(connect(mapStateToProps, mapDispatchToProps)(IndexRoutes))
root.render(
<Provider store={store}>
<Router>
<IndexRouter />
</Router>
</Provider>,
document.getElementById('root')
);
The console.log() returns user: null
, which is causing the problem. I am positively loggedIn to the app, but still showing user null.
fetching displayName and photoURL using props
const UserInfo = (props) => {
return (
<div>
<Box
display={'flex'}
flexDirection={'row'}
alignItems='center'
justifyContent={'center'}
color='white'
paddingTop={2}
paddingBottom={2}
sx={{height: '100%', flex: 1}}
>
<Avatar
alt='profile-pic'
src={props.user.photoURL}
/>
<Typography
sx={{ml: 10}}
>
{props.user.displayName}
</Typography>
</Box>
</div>
)
}
const mapStateToProps = (state) => {
return {
user: state.user.currentUser
}
}
export default connect(mapStateToProps)(UserInfo)
But, whenever I refresh the page, I get this error uncaught typeerror cannot read property of null (reading 'displayname')
Also, I am using Firebase for backend, even if I use firebase.auth().currentUser.displayName
to show data instead of props, it still shows the same error. (although I am already authenticated and signed in).
CodePudding user response:
first time data always be null at that time they set the data so passing down to ternary expression check if data is there then set the data
<Avatar
alt='profile-pic'
src={props?.user?.photoURL}
/>
<Typography
sx={{ml: 10}}
>
{props?.user?.displayName}
</Typography>