'How to fix the re- render array for each post from backend to frontend
when I am trying to make a post request then it renders whole a new array and therefore it causes multiple posts and in that array it makes whole posts re-render...
Pls, help me to figure out the problem which I am facing right now...
in-browser console which is a problem img is blw...
from backend node js {post route}
const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require ('path');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`);
}
});
const uploadImg = multer({
storage: storage,
fileFilter : (req, file, cb) => {
// reject a file
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
console.log('only jpeg and png are accepted!!!')
cb(null, false)
}
},
limits: {
fileSize: 1024 * 1024 * 5
},
}
).single('image');
const {Posts} = require('../models/Posts');
// Get All post
router.get('/posts', (req, res, next) => {
Posts.find({}, (err, data) => {
if (!err) {
res.send(data);
} else {
console.log(err);
}
});
});
router.post('/posts/add', uploadImg, (req, res, next) => {
if (!req.file) return res.send('Please upload a file');
console.log(req.body);
const pos = new Posts({
title: req.body.title,
image: req.file.filename,
HeadingTitle: req.body.HeadingTitle,
datetime: req.body.datetime,
smallTitle: req.body.smallTitle,
MoviesContent: req.body.MoviesContent,
DownloadLinkButtonsHeading: req.body.DownloadLinkButtonsHeading,
Buttons: req.body.Buttons,
allCategories: req.body.allCategories,
});
pos.save((err, data) => {
const image = `http://localhost:5000/${req.file.filename}`
res.status(200).json({
code: 200, message: 'post Added Sucessfully',
addPosts: data,
image: image
})
})
});
// Get Single ID
router.get('/posts/:id', (req, res, next) => {
Posts.findById(req.params.id, (err, data) => {
if (!err) {
res.send(data);
} else {
console.log(err);
}
});
});
// Update post
router.put('/posts/edit/:id', (req, res, next) => {
if (!req.file) return res.send('Please upload a file');
const pos = {
post: req.body,
title: req.body.title,
image: req.file.filename,
HeadingTitle: req.body.HeadingTitle,
datetime: req.body.datetime,
smallTitle: req.body.smallTitle,
MoviesContent: req.body.MoviesContent,
DownloadLinkButtonsHeading: req.body.DownloadLinkButtonsHeading,
Buttons: req.body.Buttons,
allCategories: req.body.allCategories,
};
Posts.findByIdAndUpdate(req.params.id, { $set: pos }, { new: true }, (err, data) => {
if (!err) {
res.status(200).json({
code: 200, message: 'post Updated Successfully',
updatePosts: data
})
} else {
console.log(err);
}
});
});
// Delete post
router.delete('/posts/:id', (req, res, next) => {
Posts.findByIdAndRemove(req.params.id, (err, data) => {
if (!err) {
res.status(200).json({
code: 200, message: 'post Deleted Successfully',
deletePosts: data
});
} else {
console.log(err);
}
});
})
module.exports = router
post schema from backend
const mongoose = require('mongoose');
const Posts = mongoose.model('Posts', {
title: {
type: String
},
image: {
type: String
},
HeadingTitle: {
type: String
},
datetime: {
type: Number
},
smallTitle: {
type: String
},
MoviesContent: {
type: String
},
DownloadLinksButtonsHeading: {
Buttons: {
type: String
}
},
allCategories:{
type:String
}
});
module.exports = {Posts}
frontend code for mapping all post
import React, { useState, useEffect } from 'react'
import './Section.css'
import {
BrowserRouter as Router,
Link
} from "react-router-dom";
// import api from './components/api/post';
function Section() {
const [posts, setPosts] = useState([]);
const Fetchpost = async () => {
const response = await fetch('http://localhost:5000/posts');
setPosts(await response.json());
}
useEffect(() => {
Fetchpost();
}, []);
console.log(posts);
return (
<>
{
posts.map((post) => {
return (
<div key= {post._id}className="samplecontainer">
<div className="r1">
<>
<img src={`http://localhost:5000/${post.image}`} alt="myimg" />
<Link to={post.title}></Link>
<p className="heading">{post.title}</p>
</>
</div>
</div>
)
})
}
</>
)
}
export default Section
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|