仅显示 Post 该用户 Post 在带有服务器端的 Reactjs 中编辑的是 Node Js,Mongodb

Showing only Post That user Posted in Reactjs with Server Side is Node Js, Mongodb

我想要什么? 我想添加仅登录用户 post 的 post。此 post 仅显示我的项目组件页面。这是我的所有代码。当我登录并尝试添加 post 然后检查我的项目组件页面时。此页面显示所有 post。 app.getServer url '/product' 它收集```电子邮件对象''' 谢谢。

async function run() {
  try {
    await client.connect();
    const productCollection = client.db("data").collection("product");

    app.get("/product", async (req, res) => {
      const query = {};
      const cursor = productCollection.find(query);
      const products = await cursor.toArray();
      res.send(products);
    });

    app.get("/product", async (req, res) => {
      const email = req.query.email;
      const query = {email: email};
      const cursor = productCollection.find(query);
      const products = await cursor.toArray();
      res.send(products);
    });

    app.get("/product/:id", async (req, res) => {
      const id = req.params.id;
      const query = { _id: ObjectId(id) };
      const product = await productCollection.findOne(query);
      res.send(product);
    });

    app.post("/product", async (req, res) => {
      const newProduct = req.body;
      const result = await productCollection.insertOne(newProduct);
      res.send(result);
    });

    // DELETE
    app.delete("/product/:id", async (req, res) => {
      const id = req.params.id;
      const query = { _id: ObjectId(id) };
      const result = await productCollection.deleteOne(query);
      res.send(result);
    });

    app.put('/update-quantity/:id', async (req, res) => {
      const id = req.params.id;
      const updatedInventoryInfo = req.body;
      const filter = { _id: ObjectId(id) };
      const options = { upsert: true };
      const updatedDoc = {
          $set: {
              quantity: updatedInventoryInfo.quantity,
              sold: updatedInventoryInfo.sold
          }
      }
      const result = await productCollection.updateOne(filter, updatedDoc, options);
      res.send(result);
  })
  } finally {
  }
}

客户端代码 React Js

import axios from "axios";
import React, { useEffect } from "react";
import { Button, Col, Container, Row } from "react-bootstrap";
import { useAuthState } from "react-firebase-hooks/auth";
import { useNavigate } from "react-router-dom";
import auth from "../../firebase.init";
import useProduct from "../../Hooks/useProduct";

const MyItem = () => {
  const [user] = useAuthState(auth);
  const [products, setProducts] = useProduct();
  const navigate = useNavigate();

  useEffect(() => {
    const getItems = async () => {
      const email = user.email;
      console.log(email);
      const url = `http://localhost:5000/product?email=${email}`;
      const { data } = await axios.get(url);
      setProducts(data);
    };
    getItems();
  }, [user]);

  const handelDelete = (id) => {
    const process = window.confirm(
      "Are you sure you want to delete this item?"
    );
    if (process) {
      const url = `http://localhost:5000/product/${id}`;
      fetch(url, {
        method: "DELETE",
      })
        .then((res) => res.json())
        .then((result) => {
          console.log(result);
          setProducts(products.filter((product) => product._id !== id));
        });
    }
  };

  const navigateToProductDetails = (id) => {
    navigate(`/product/${id}`);
  };

  return (
    <>
      <Container>
        <Row>
          {products.map((product, index) => {
            return (
                <Col key={index} md={4}>
                  <div className="product-aria">
                    <img src={product.img} alt="" />
                    <div>
                      <h1>{product.name}</h1>
                      <p>Details:{product.content}</p>
                      <div className="d-flex gap-3 flex-wrap justify-content-center">
                        <Button
                          onClick={() => navigateToProductDetails(product._id)}
                          variant="primary"
                        >
                          Manage
                        </Button>
                        <Button
                          onClick={() => handelDelete(product._id)}
                          variant="danger"
                        >
                          Delete
                        </Button>
                      </div>
                    </div>
                  </div>
                </Col>
            );
          })}
        </Row>
      </Container>
    </>
  );
};

export default MyItem;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

节点Js

您正在使用相同的 api url /products。所以我改变了这个 url 并且它现在可以正常工作了。

app.get("/products", async (req, res) => {
      const query = {};
      const cursor = productCollection.find(query);
      const products = await cursor.toArray();
      res.send(products);
    });

    app.get("/product", async (req, res) => {
      const email = req.query.email;
      const query = {email: email};
      const cursor = await productCollection.find(query).toArray();
      res.send(cursor);
    });

    app.get("/product/:id", async (req, res) => {
      const id = req.params.id;
      const query = { _id: ObjectId(id) };
      const product = await productCollection.findOne(query);
      res.send(product);
    });

    app.post("/products", async (req, res) => {
      const newProduct = req.body;
      const result = await productCollection.insertOne(newProduct);
      res.send(result);
    });

我认为您使用的是自定义挂钩。 useProduct() 我只是评论它并使用 useState() 钩子并将依赖性 useEffect 钩子 user 更改为 email。这是我的代码。

const [user] = useAuthState(auth);
  const { email } = user;
  console.log(email);
  // const [products, setProducts] = useProduct();
  const [products, setProducts] = useState([]);
  const navigate = useNavigate();

  useEffect(() => {
    const getItems = async () => {
      // console.log(email);
      const url = `http://localhost:5000/product?email=${email}`;
      const { data } = await axios.get(url);
      setProducts(data);
    };
    getItems();
  }, [email]);