Next.js Full Course Level3

1مُقدمة المُستوى الثالث
2Design Admin Page

Download files

3Store data in mongodb

Download files

4Send file(image) to Back-end

👉 1- Useeo.target.files[0]

 
<input
 type="file"
 onChange={(eo) => setImg(eo.target.files[0])}
/>

👉 2- Use new FormData()

 
const handleSubmit = async (eo) => {
 const formData = new FormData();
 formData.set("file", file);
 formData.set("title", title);
 formData.set("price", price);
 formData.set("description", description);

const resAddProduct = await fetch("api/addProduct", {
  method: "POST",
  body: formData,
});
}

👉 3- Use request.formData();in route.js

 export async function POST(request) {

   const dataFromFrontend = await request.formData();
   const file = dataFromFrontend.get("file");
   const title = dataFromFrontend.get("title");
   const price = dataFromFrontend.get("price");
   const description = dataFromFrontend.get("description");

return NextResponse.json({ msg: "Done!!" });
}
 

Download files

5 Upload Images to Cloudinary

المصدر

👉 1- npm i cloudinary

👉 2- Create a function to upload image to cloudinary.

👉 in uploadFunctions.js

 
const { Readable } = require("stream");
const cloudinary = require("cloudinary").v2;
 
cloudinary.config({
  cloud_name: process.env.TESTTT,
  api_key: process.env.TESTTT,
  api_secret: process.env.TESTTT,
});
 
const options = {
  stream: true,
};
 
export async function uploadStream(buffer) {
  return new Promise((res, rej) => {
    const theTransformStream = cloudinary.uploader.upload_stream(
      options,
      (err, result) => {
        if (err) return rej(err);
        res(result);
      }
    );
    let str = Readable.from(buffer);
    str.pipe(theTransformStream);
  });
}

👉 3- In route.js


const productImg = objFromFrontEnd.get("productImg")
 
const bytes = await productImg.arrayBuffer();
const buffer = Buffer.from(bytes);
const uploadedImg = await uploadStream(buffer)
console.log(uploadedImg)

Download files

6Task Solution

Download files

7⭐ Fetching data in client component
const [data, setData] = useState([]);

useEffect(() => {
  const getData = async () => {
    const res = await fetch("http://localhost:3000/api/getProducts");
    if (!res.ok) {
      notFound();
    }
    const data = await res.json();
    setData(data);
  };
  getData();
}, []);

Download files

8Get All Products from mongoDB

Model.create()=> to store data in DB.

Model.findOne()=> to find a specific object in DB.

Model.find()=> to find all data in DB as Array.

route.js

Download files

9Get only one product using searchParams

in route.jsconst id = request.nextUrl.searchParams.get("id")

Download files

10Delete Product from MongoDB

Model.create()=> to store data in DB.

Model.findOne()=> to get a specific object in DB.

Model.find()=> to get all data in DB as Array.

Model.deleteOne()=> to DELETE a specific object from DB.

Download files

11Delete image from cloudinary
 
const cloudinary = require("cloudinary").v2;

cloudinary.config({
   cloud_name: process.env.CLOUD_NAME,
   api_key: process.env.API_KEY,
   api_secret: process.env.API_SECRET,
 });
 
await cloudinary.uploader.destroy(public_id);

Download files

12Update Product

Model.create()=> to store data in DB.

Model.findOne()=> to get a specific object in DB.

Model.find()=> to get all data in DB as Array.

Model.deleteOne()=> to DELETE a specific object from DB.

Model.updateOne({ }, { })=> to UPDATE a specific object in DB.

Download files

13Task Solution
14Task Solution

Download files

😡
انت مشغل الـ AdBlock !!

ياريت تقفله لوسمحت 😊 😊

تنبيه هام ✋

إذا كانت الإعلانات مزعجة بالنسبة لك، فيُمكنك التبرع ب50$ وسيتم إيقاف الإعلانات لمدة شهر لجميع زوار الموقع 🧡 ويُمكنك التواصل معنا عن طريق صفحة الفيس بوك