lundi 28 septembre 2020

Prop passed in to component is undefined

I am building an ecommerce website which includes a cart for each user. I want to pass the state of cart to a component using props

In App.js -

<Header cart={cart} />

In Header.js -

function Header({ cart }) {
  console.log(cart);
}

I have checked console.log(cart) in App.js and it gives me the desired and correct array of objects.

I pass in this state as a prop to Header Component and then I want to display the number of items in the cart.

But, the console.log(cart) in Header.js gives me undefined.

What am I doing wrong here? Thanks in advance.

App.js -->

function App() {
  const [{ bag }, dispatch] = useStateValue();
  const [cart, setCart] = useState([]);
  console.log("CART -", cart);

  useEffect(() => {
    //will only load when app component loads
    auth.onAuthStateChanged((authUser) => {
      console.log("USER ->", authUser);

      if (authUser) {
        dispatch({
          type: "SET_USER",
          user: authUser,
        });

        db.collection("users")
          .doc(authUser.uid)
          .collection("cart")
          .onSnapshot((snapshot) =>
            setCart(
              snapshot.docs.map((doc) => ({
                id: doc.data().id,
                image: doc.data().image,
                productName: doc.data().productName,
                productPrice: doc.data().productPrice,
              }))
            )
          );
      } else {
        dispatch({
          type: "SET_USER",
          user: null,
        });
      }
    });
  }, []);

  return (
    <Router>
      <div className="App">
        <Switch>
          <Route exact path="/payment">
            <Header cart={cart} />
            <Elements stripe={promise}>
              <Payment />
            </Elements>
          </Route>
          <Route exact path="/login">
            <Login />
          </Route>

          <Route exact path="/checkout">
            <Header />
            {/* <CategoriesHeader /> */}
            <Checkout />
          </Route>

          <Route exact path="/">
            <Header />
            <CategoriesHeader />
            <Home />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

export default App;



Aucun commentaire:

Enregistrer un commentaire