i'm working with react, redux and firestore I'm trying to pass user to a component and then with uid pull some data from firestore. but for unknown (to me) reason i always get undefined at first but on second render i get the correct data.
App.js:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
user: {},
};
}
async componentDidMount() {
const { setCurrentUser } = this.props;
this.unsubscribeFromAuth = await FB.auth.onAuthStateChanged((user) => {
console.log('User:', user);
if (user) {
this.setState({ user });
localStorage.setItem('user', user.uid);
} else {
this.setState({ user: null });
localStorage.removeItem('user');
}
setCurrentUser(user);
});
}
render() {
return (
<Router>
<div className='App'>
<Header />
<Routes>
<Route path='/' exact element={<Page/>} />
</Routes>
<Footer />
</div>
</Router>
);
}
}
const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser,
});
const mapDispatchToProps = (dispatch) => ({
setCurrentUser: (user) => dispatch(setCurrentUser(user)),
});
export default connect(mapStateToProps, mapDispatchToProps)(App);
user action
import { UserActionTypes } from "./user.types";
export const setCurrentUser = (user) => ({
type: UserActionTypes.SET_CURRENT_USER,
payload: user,
});
user selecter:
import { createSelector } from "reselect";
const selectUser = (state) => state.user;
export const selectCurrentUser = createSelector([selectUser],(user) => .currentUser
page:
const Page=({ currentUser }) => {
const [user, setUser] = useState([]);
const userDB = async (currentUser) => {
console.log('userDB START:', currentUser);
if (!currentUser) return;
const userUID = currentUser.currentUser.uid;
const ref = doc(firestore, 'users', userUID);
const data = await getDoc(ref);
const dataSet = await data.json();
if (data) {
//NOTE THAT I NEVER GET IN HERE
console.log('docSnap.data: ', data.data());
setUser(data.data());
} else {
console.log('No such document!');
}
};
useEffect(() => {
userDB();
}, []);
return ();
};
const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser,
});
export default connect(mapStateToProps)(Page)
output is:
userDB START: undefined
Thank you in advance!
useEffect(() => {
userDB(currentUser);
}, []);
In case mapStateToProps is actually undefined like your title says
<Route path='/' exact element={<Page currentUser={this.state.user} />} />