2

Just getting started with React / Redux.

I've implemented auth with Firebase, and able to store the logged-in user in Redux store:

App.js:

import React, { useEffect } from "react";
import { Switch, Route } from "react-router-dom";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

import Login from "./pages/auth/Login";
import Register from "./pages/auth/Register";
import Home from "./pages/Home";
import Header from "./components/nav/Header";
import RegisterComplete from "./pages/auth/RegisterComplete";

import { auth } from "./firebase";
import { useDispatch } from "react-redux";

const App = () => {
  const dispatch = useDispatch();

  // to check firebase auth state
  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged(async (user) => {
      if (user) {
        const idTokenResult = await user.getIdTokenResult();
        console.log("user", user);
        dispatch({
          type: "LOGGED_IN_USER",
          payload: {
            email: user.email,
            token: idTokenResult.token,
          },
        });
      }
    });
    // cleanup
    return () => unsubscribe();
  }, [dispatch]);

  return (
    <>
      <Header />
      <ToastContainer />
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/login" component={Login} />
        <Route exact path="/register" component={Register} />
        <Route exact path="/register/complete" component={RegisterComplete} />
      </Switch>
    </>
  );
};

export default App;

My Redux store is defined in Index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter} from "react-router-dom";
import 'antd/dist/antd.css';
import { createStore } from "redux";
import { Provider } from "react-redux";
import { composeWithDevTools } from "redux-devtools-extension";
import rootReducer from "./reducers";

const store = createStore(rootReducer, composeWithDevTools());

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);

In my Header component I want to display the email of the logged-in user, which is being stored in Redux store like "store.user.email", which I can clearly see in the Redux console tab in the browser.

What is the proper way of getting a hold of 'store' in my Header.js component?

0

2 Answers 2

4

Since you're using functional components, you can use useSelector:

import { useSelector } from 'react-redux';

const Header = () => {
  const email = useSelector(store => store.user.email);

   // do whatever with the email
};

The other option, which is available to all types of components, is to use connect with a mapStateToProps function:

import { connect } from 'react-redux';

const Header = ({ email }) => {
  // do whatever with the email prop
};

const mapStateToProps = (store) => ({
  email: store.user.email
});

export default connect(mapStateToProps)(Header);

For more information, here's the documentation on useSelector: https://react-redux.js.org/api/hooks#useselector

And here's the documentation on connect: https://react-redux.js.org/api/connect

Sign up to request clarification or add additional context in comments.

Comments

-1

you can try this as well. add this part to the Header component

 componentDidMount() { 
        store.subscribe(() => { 
            this.setState({})
        })
    }

then add the following code to the index.jsx

store.subscribe(()=> { 
ReactDOM.render(
 <App />,
 document.getElementById('root')
)
})

I am new to React as well, so I have limited knowledge on it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.