Data not loading on front end - node.js

I have a dashboard displaying links based on user type when you register you choose your role 1, 2, 3, 4, 5. Everything works fine except when pulling data from the DB and showing it on the front end. On insomnia if I send a command adminId: 1 it returns the correct data. Below is the code where I tie the adminId to the data to display the correct links but nothing happens. If anyone can help it would be great! I am storing the adminId in userData and pulling the links from the backend using axios.
const { userData } = useContext(UserContext);
const history = useHistory();
const [links, setLinks] = useState();
const currAdmin = () => {
currAdmin = userData.user.adminId;
}
useEffect(() => {
if (!userData.user)
history.push("/");
const checkAdmin = async () => {
const adminRes = await axios.get('http://localhost:9000/Links/all', { currAdmin });
setLinks(adminRes.data);
};
checkAdmin();
});
return (
<div className="dashboard">
<Header />
<br />
<br />
<h3> Admin Type: </h3>
<ListGroup className="linklist" >
{links && links.map(e => (
<ListGroup.item key={e.adminId}>
{e.links}
</ListGroup.item>
))}
</ListGroup>
</div>
);
}

For your reference, Please let me know if it will help you.
import React, {useState, useEffect} from 'react';
import axios from 'axios';
function FetchAPIData(props) {
const [myData, setData] = useState({ data:[] });
useEffect(() => {
const fetchData = async () => {
const result = await axios(`http://dummy.restapiexample.com/api/v1/employees`,);
setData(result.myData);
};
fetchData();
}, []);
return (
<div>
<span>{JSON.stringify(myData)}</span>
<ul>
{
myData.data.map(item => {
<li key={item.id}>
{item.employee_name}
</li>
})
}
</ul>
</div>
);
}
export default FetchAPIData;

Related

Why data fetched from backend shows in console but not in the webpage?

Here I've fetched workouts from backend through api. It shows output in the console but unable to map through workouts state in the webpage.
import React, { useEffect, useState } from "react";
const Home = () => {
const [workouts, setWorkouts] = useState([]);
useEffect(() => {
const fetchWorkouts = async () => {
const response = await fetch("http://localhost:4000/api/workouts");
const json = await response.json();
if (response.ok) {
console.log('success');
console.log(json);
setWorkouts(json);
}
};
fetchWorkouts();
}, []);
return (
<div className="home">
<div className="workouts">
{workouts &&
workouts.map((workout) => {
<p key={workout._id}>{workout.title}</p>;
})}
</div>
</div>
);
};
export default Home;
You forgot to return it. Do this:
return <p key={workout._id}>{workout.title}</p>;
or you can also do this:
{workouts?.map((workout) => (
<p key={workout._id}>{workout.title}</p>
))}
You can remove the bracket on the map:
workouts.map((workout) =>
<p key={workout._id}>{workout.title}</p>;
)}
You're not returning anything. Either explicitly use the return keyword to return the element or You can do this in a more appropriate way like this.
{
workouts &&
workouts.map((workout) => (
<p key={workout._id}>{workout.title}</p>
))
}

How to UPDATE multiple ID's using one endpoint in React+Node+SQL Server environment

I'm trying to use the UPDATE endpoint to update the records in SQL Server. So the end user is searching the record by Order Number which could contain multiple records under that.
Refer the following figure 1 & 2. The end user is prompt to enter an Order Number and whatever the number of records it contains in the SQL Server database would show up.
Figure 1
Figure 2
Now my goal is, if the user wants to update any of those Email/Fax fields and once they click UPDATE it should update in the SQL Server database. I have got to a point that I get only one of the ID's but not the other one. So it throws me the error PUT http://localhost:5000/api/customerOrder/69071 404 (Not Found)
Can any of you help me with a way to correctly update this without getting any errors?
Following is my code and what I have tried so far :
FetchOrderDetails.js
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import '../App.css';
const FetchOrderDetails = ({ord_no,ID}) => {
const [data, setData] = useState([]);
const url = `http://localhost:5000/api/customerOrder/${ord_no}`
useEffect(() => {
axios.get(url)
.then(response => {
console.log(response.data)
setData(response.data)
})
.catch((err) => console.log(err));
}, [url]);
const url2 = `http://localhost:5000/api/customerOrder/${ID}`
const onSubmit = () => {
axios.put(url2)
.then((response) => {
if (response.status === 200) {
alert("Comment successfully updated");
ID.history.push(`/customerOrder/${ord_no}`);
} else Promise.reject();
})
.catch((err) => alert("Something went wrong"));
}
if(data) {
return(
<div>
{data.map((order) => (
<div key={order.ID}>
<br></br>
ID : {order.ID}
<br></br>
Email/Fax: <input defaultValue={order.cmt} placeholder="Sales Ack Email" id="salesAck" style={{width: "370px"}} />
</div>
))}
<div>
<br></br>
<br></br>
<button onClick={onSubmit}>Update</button>
</div>
</div>
)
}
return (
<h1>Something went wrong!</h1>
)
}
export default FetchOrderDetails;
EmailFaxDetails.js
import React, { useState,useEffect } from 'react'
import FetchOrderDetails from './FetchOrderDetails';
import axios from 'axios'
import '../App.css';
const EmailFaxDetails = () => {
const [orderNumber, setOrderNumber] = useState('');
const [id, setId] = useState([]);
const [isShown, setIsShown] = useState(false);
const url = `http://localhost:5000/api/customerOrder/${orderNumber}`
useEffect(() => {
axios.get(url)
.then(response => {
console.log(response.data)
setId(response.data)
})
.catch((err) => console.log(err));
}, [url]);
const handleChange = event => {
setOrderNumber(event.target.value);
console.log(event.target.value);
};
const handleClick = event => {
event.preventDefault();
setIsShown(true);
console.log(orderNumber);
}
return(
<div>
<br></br>
<br></br>
Order Number: <input placeholder="Order Number" type="text" id="message" name="message" onChange={handleChange} value={orderNumber} autoComplete="off" />
{id.map((idnum) => (
<div key={idnum.ID}>
{isShown && <FetchOrderDetails ord_no={orderNumber} ID={idnum.ID}/>}
</div>
))}
<button onClick={handleClick}>Search</button>
</div>
)
}
export default EmailFaxDetails;
Here's my table structure example too, so there can be multiple ID's under one Order Number.
Appreciate your help!

Builds a chat app in React, using axios and firestore

Please I would be happy if anyone would help me
I have a problem, I can not use the server-side functions, I call the functions with axios, and execute it in react hooks.
I actually build chat, which is why I use react hook, because I want messages to be updated all the time.
I also use firestore. There I save the messages, and receive them through the server side function.
It's a component of the chat - it's causing me problems, I do not understand why.
The server side functions work great, I tested them in postman, and they worked. The problem is that I can't run them in a function component. I do not know what I'm doing wrong.
The error I get here is in the line chat.users.length> 0?, When I make this comparison I get that chat.users is undefined, but I do not understand why because I initialize it at first, using a server side function , Which gives the necessary information
I'm very confused, and I'm new here on the site, I'm trying to figure out why it has not worked for two whole days
I think I might be confused by syntax, for example using an unnecessary dispatch inside component of the chat
i got this error:
enter image description here
component of the chat
import React, { useEffect, useState } from 'react';
import './style.css';
import { useDispatch, useSelector } from 'react-redux';
import { getRealtimeUsers, updateMessage, getRealtimeConversations } from '../../redux/actions/chatActions';
import { Fragment } from 'react';
const User = (props) => {
const { chat, onClick } = props;
return (
<div onClick={() => onClick(chat)} className="displayName">
<div className="displayPic">
<img src="https://i.pinimg.com/originals/be/ac/96/beac96b8e13d2198fd4bb1d5ef56cdcf.jpg" alt="" />
</div>
<div style={{ display: 'flex', flex: 1, justifyContent: 'space-between', margin: '0 10px' }}>
<span style={{ fontWeight: 500 }}>{chat.firstName} {chat.lastName}</span>
<span className={chat.isOnline ? `onlineStatus` : `onlineStatus off`}></span>
</div>
</div>
);
}
const HomePage = (props) => {
const dispatch = useDispatch();
const user = useSelector(state => state.user.credentials);
const chat = useSelector(state => state.chat);
const [chatStarted, setChatStarted] = useState(false);
const [chatUser, setChatUser] = useState('');
const [message, setMessage] = useState('');
const [userUid, setUserUid] = useState(null);
let unsubscribe;
useEffect(() => {
//unsubscribe = dispatch(getRealtimeUsers(user.handle))
dispatch(getRealtimeUsers());
}, []);
//console.log(user);
//componentWillUnmount
useEffect(() => {
return () => {
//cleanup
//unsubscribe.then(f => f()).catch(error => console.log(error));
unsubscribe.then(f => f()).catch(error => console.log(error));
}
}, []);
//function
const initChat = (chat) => {
setChatStarted(true)
setChatUser(`${chat.firstName} ${chat.lastName}`)
setUserUid(chat.handle);
console.log(chat);
dispatch(getRealtimeConversations({ uid_1: user.handle, uid_2: chat.handle }));
}
const submitMessage = (e) => {
const msgObj = {
user_uid_1: user.handle,
user_uid_2: userUid,
message
}
if (message !== "") {
dispatch(updateMessage(msgObj))
.then(() => {
setMessage('')
});
}
//console.log(msgObj);
}
return (
<Fragment>
<section className="container">
<div className="listOfUsers">
{console.log(chat)}
{
//chat.users != undefined
chat.users.length > 0 ?
chat.users.map(user => {
return (
<User
onClick={initChat}
key={user.handle}
user={user}
/>
);
})
: null
}
</div>
<div className="chatArea">
<div className="chatHeader">
{
chatStarted ? chatUser : ''
}
</div>
<div className="messageSections">
{
chatStarted ?
chat.conversations.map(con =>
<div style={{ textAlign: con.user_uid_1 == user.handle ? 'right' : 'left' }}>
<p className="messageStyle" >{con.message}</p>
</div>)
: null
}
</div>
{
chatStarted ?
<div className="chatControls">
<textarea
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Write Message"
/>
<button onClick={submitMessage}>Send</button>
</div> : null
}
</div>
</section>
</Fragment>
);
}
export default HomePage;
This is the axios:
app.get('/realtimeUsers', FBAuth, getRealtimeUsers );
app.post('/updateMessage', FBAuth, updateMessage);
app.get('/realtimeConversations', FBAuth, getRealtimeConversations);
And this is the server side functions - They work 100% - I checked them many times and they worked.:
const { db } = require('../util/admin');
exports.getRealtimeUsers = (req, res) => {
db.collection("users")
.onSnapshot((querySnapshot) => {
const users = [];
querySnapshot.forEach(function (doc) {
if (doc.data().handle != req.user.handle) {
users.push(doc.data());
}
});
return res.json(users);
});
}
exports.updateMessage = (req, res) => {
db.collection('conversations')
.add({
...req.body,
isView: false,
createdAt: new Date()
})
.then(() => {
return res.json({ message: "Conversations added successfully" });
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code });
});
}
exports.getRealtimeConversations = (req, res) => {
console.log(JSON.stringify("testing"));
console.log(JSON.stringify(req.query));
console.log(JSON.parse(req.query.user));
console.log(JSON.parse(req.query.user).uid_1);
console.log(JSON.parse(req.query.user).uid_2);
db.collection('conversations')
.where('user_uid_1', 'in', [JSON.parse(req.query.user).uid_1, JSON.parse(req.query.user).uid_2])
.orderBy('createdAt', 'asc')
.onSnapshot((querySnapshot) => {
const conversations = [];
querySnapshot.forEach(doc => {
console.log(JSON.stringify(doc));
if (
(doc.data().user_uid_1 == JSON.parse(req.query.user).uid_1 && doc.data().user_uid_2 == JSON.parse(req.query.user).uid_2)
||
(doc.data().user_uid_1 == JSON.parse(req.query.user).uid_2 && doc.data().user_uid_2 == JSON.parse(req.query.user).uid_1)
) {
conversations.push(doc.data())
}
});
console.log(conversations);
return res.json(conversations);
})
//return res.json([]);
}
this is the actions that used in the client side, here i call to the axios:
import { userConstants } from "../types";
import axios from 'axios';
export const getRealtimeUsers = () => (dispatch) => {
dispatch({ type: `${userConstants.GET_REALTIME_USERS}_REQUEST` });
axios
.get('/realtimeUsers')
.then((res) => {
console.log(res);
dispatch({
type: `${userConstants.GET_REALTIME_USERS}_SUCCESS`,
payload: res.data
});
})
.catch((err) => console.log(err))
}
export const updateMessage = (msgObj) => (dispatch) => {
axios.post('/updateMessage', msgObj)
.then(() => { })
.catch((err) => console.log(err));
}
export const getRealtimeConversations = (user) => (dispatch) => {
//user = { uid_1: "from visualcode", uid_2: "userUid" };
console.log(JSON.stringify(user));
axios.get('/realtimeConversations',
{
params: {
user: JSON.stringify(user)
//uid_1:JSON.stringify("user.handle"),
//uid_2:JSON.stringify("userUid")
}
}
)
.then((res) => {
dispatch({
type: userConstants.GET_REALTIME_MESSAGES,
payload: res.data
});
})
.catch((err) => console.log(err))
}
I am not able to understand your whole code flow, i.e., how the chat.users will be populated before initChat is called.
But still, for your problem, you should always put a check for undefined values while iterating through an array.
<div className="listOfUsers">
{console.log(chat)}
{
//chat.users != undefined
chat && chat.users && chat.users.length > 0 &&
chat.users.map(user => {
return (
<User
onClick={initChat}
key={user.handle}
user={user}
/>
);
})
}
</div>

How can I map string array taken from mongoDB and show one specific title/body per post

I have a RESTful app built with React and Express Node, in it is a simple form with body and title inputs overlaid on a background image, when user clicks save, they are directed to another component with axios.get request displaying the their post.
My goal is to retrieve the data saved and display the image/posts in an array. Right now I am just testing the post retrieval, I will work on the images later. When testing the route in Postman, I am able to see all my posts using http://localhost:5000/getall, however when I use this path in my axios.get request I am seeing all the posts in a clutter, not separated: see example in image below. To access the arrays I us a <Card /> I import the a Card component (`) in my SharewallComp.js file.
How can I map this string array taken from mongo dB and show just one title/body per post?
I tried the following:
Retrieve data by id: let res = await axios.get(http://localhost:5000/getall${match.params.id}); but I get TypeError: Cannot read property 'params' of undefined.
I also tried the below with out match params and my result was just the numbers see error screenshot below:
<Card.Title className="text-center mt-5">
Title: {(title).map((t, index) => (
<Card.Text key={index} className="text-light"> {(t, index)} </Card.Text>
))}
Body: {(body).map((b, index) => (
<Card.Text key={index} className="text-light"> {(b, index)} </Card.Text>
))}
Here is my attempt: Mapping is not my strongest skill. Any help I appreciate so much!
import React, { useState, useEffect } from "react";
import axios from "axios";
import Cards from "./Cards";
const ShareWallComp = ({ match }) => {
const [url, setUrl] = useState([]);
const history = useHistory();
const loadimg = async () => {
try {
let res = await axios.get(
`http://localhost:5000/geturls/${(match.params.name="grace")}`
);
setUrl(res.data.map((d) => d.url));
} catch (error) {
console.log(error);
}
};
useEffect(() => {
// login code
loadimg();
}, []);
return (
<div className="getcross">
<Container className="mt-5 ml-auto mr-auto">
<div className="mt-4">
<Navi />
</div>
<h1 className="text-center">
ShareVerse
<span className="text-success"> Wall</span>
</h1>
<div>
<div className="shadow p-3 mb-5 bg-white rounded">
<Card className="bg-dark shadow text-white">
{url
.filter((name) => name.includes("grace"))
.map((urlData) => (
<Card.Img key={url.name} src={urlData} alt="Card image" />
))}
<Card.ImgOverlay>
<div className="text-center"><Cards /></div>
</Card.ImgOverlay>
</Card>
</div>
</div>
</Container>
</div>
);
};
export default ShareWallComp;
Here is the component where I have arrays for inputs
import React, { useState, useEffect } from "react";
import axios from "axios";
const ComponentName = (props) => {
const [body, setBody] = useState([]);
const [title, setTitle] = useState([]);
const loadData = async () => {
try {
// let res = await axios.get(
let res = await axios.get(`http://localhost:5000/getall`);
setTitle(res.data.map((t) => t.title));
setBody(res.data.map((b) => b.body));
} catch (error) {
console.log(error);
}
};
useEffect(() => {
loadData()
}, []);
return (
<div className="compoentclass">
<Container className="mt-5 ml-auto mr-auto">
<div className="text-center">
<Card.Title className="text-center mt-5">
Title: {(title).map((t) => (
<Card.Text className="text-light"> {(t)} </Card.Text>
))}
Body: {(body).map((b) => (
<Card.Text className="text-light"> {(b)} </Card.Text>
))}
</Card.Title>
</div>
</Container>
</div>
);
}
export default ComponentName;
example of posts clutered
error when retrieving data with id
the below screenshot an example of what I want my code to do:
The answer was to get all the data rather then mapping it : see the below corrected code, I hope this helps some one out there! So instead of setTitle(res.data.map((t) => t.title)); and setBody(res.data.map((t) => t.Body));, just get all the data: setPosts(res.data); Then call {post.body}
import React, { useState, useEffect } from "react";
import Container from "react-bootstrap/Container";
import Card from "react-bootstrap/Card";
import Button from "react-bootstrap/Button";
import axios from "axios";
import "./css/sharewall.css";
const ComponentName = () => {
const [posts, setPosts] = useState([]);
const [comment, setComment] = useState("");
const [id, setId] = useState("");
const loadData = async () => {
try {
let res = await axios.get(`http://localhost:5000/getall`);
setPosts(res.data);
} catch (error) {
console.log(error);
}
};
useEffect(() => {
loadData();
}, []);
return (
<div className="compoentclass">
<Container className="mt-5 ml-auto mr-auto">
<div className="text-center">
{posts.map((post, index) => (
<div>
<Card className="">
<Card.Img alt="" src={post.url} />
<Card.ImgOverlay className="overlay">
<Card.Title className="text-center mt-5">
<Card.Text className="cardStyle text-light">
{post.body}
</Card.Text>
</Card.Title>
</Card.ImgOverlay>
</Card>
{posts.map((post, index) => (
))}
</div>
</div>
))}
</div>
</Container>
</div>
);
};
export default ComponentName;

_id is missing after doing actions

i'm currently creating my first MERN App, and everything is going well, until something happened, and i'm going my try to explain because i need help !
What i'm doing is a facebook clone, where you can post something, you can delete your post and you can update your post, the logic is simple, i call dispatch to pass the data to the actions, the actions pass the data to the backend, and the backend return something to me and it saves in my store, because i'm using redux
The problem is that, when i have 2 post, and i want to delete a post, or maybe i want to edit it, the other post dissapears, it's like it loses its id and then loses the information, then i can't do anything but reaload the page, and it happens always
this is how it looks like, everything fine
Then, after trying to edit a post, the second one lost its information, and in the console, it says that Warning: Each child in a list should have a unique "key" prop, and i already gave each post the key={_id}, but the post lost it and i don't know how
Here's the code
Posts.js
import React, { useState } from "react";
import "./Posts.css";
import moment from "moment";
// Icons
import { BiDotsVertical, BiLike } from "react-icons/bi";
import { MdDeleteSweep } from "react-icons/md";
import { AiFillLike } from "react-icons/ai";
import { GrClose } from "react-icons/gr";
// Calling actions
import { deletePost, } from "../actions/posts.js";
// Gettin The Data From Redux
import { useSelector, useDispatch } from "react-redux";
const Posts = ({ setCurrentId }) => {
const [animation, setAnimation] = useState(false);
const [modal, setModal] = useState(false);
const [modalPost, setModalPost] = useState({});
// Getting The Posts
const posts = useSelector(state => state.posts);
const dispatch = useDispatch();
// Showing And Hiding Modal Window
const ModalWindow = post => {
setModalPost(post);
setModal(true);
};
// Liking the post
// const Like = id => {
// dispatch(giveLike(id));
// setAnimation(!animation);
// };
if (!posts.length) {
return <div>Loading</div>;
} else {
return (
<div className="Posts">
{/* // Modal window for better look to the post */}
{/* {modal && (
<div className="modalWindow">
<div className="container">
<div className="container-image">
<img src={modalPost.image} alt="" />
</div>
<div className="information">
<div className="container-information">
<div className="data-header">
<h2>
User <br />{" "}
<span style={{ fontWeight: "400" }}>
{moment(modalPost.createdAt).fromNow()}
</span>
</h2>
<span className="data-icon" onClick={() => setModal(false)}>
<GrClose />
</span>
</div>
<div className="message">
<h2>{modalPost.title}</h2>
<p>{modalPost.message}</p>
</div>
</div>
</div>
</div>
</div>
)} */}
{/* */}
{posts.map(post => {
const { _id, title, message, image, createdAt, likes } = post;
return (
<div className="Posts-container" key={_id}>
<div className="Fit">
<div className="Fit-stuff">
<h2 className="Fit-stuff_title">
User <br />{" "}
<span style={{ fontWeight: "400" }}>
{moment(createdAt).fromNow()}
</span>
</h2>
<a
className="Fit-stuff_edit"
href="#form"
onClick={() => setCurrentId(_id)}
>
<BiDotsVertical />
</a>
</div>
<div className="Fit-data">
<h2 className="Fit-data_title">{title}</h2>
<p className="Fit-data_message">{message}</p>
{image ? (
<div className="Fit-img">
<img
onClick={() => ModalWindow(post)}
src={image}
alt=""
/>
</div>
) : (
<div></div>
)}
</div>
<div className="Fit-shit">
<span>
{animation ? (
<AiFillLike className="fullLightBlue" />
) : (
<BiLike />
)}
{likes}
</span>
<span onClick={() => dispatch(deletePost(_id))}>
<MdDeleteSweep />
</span>
</div>
</div>
</div>
);
})}
</div>
);
}
};
export default Posts;
The form where i call update and create Post
import React, { useState, useEffect } from "react";
import Filebase from "react-file-base64";
// For the actions
import { useDispatch, useSelector } from "react-redux";
import { createPost, updatePost } from "../actions/posts.js";
import {
Wrapper,
FormContainer,
Data,
DataInput,
SecondDataInput,
FormContainerImg,
FormContainerButtons,
Buttons
} from "./FormStyled.js";
const Form = ({ currentId, setCurrentId }) => {
const [formData, setFormData] = useState({
title: "",
message: "",
image: ""
});
const specificPost = useSelector(state =>
currentId ? state.posts.find(p => p._id === currentId) : null
);
// Sending The Data And Editing The data
const dispatch = useDispatch();
useEffect(() => {
if (specificPost) setFormData(specificPost);
}, [specificPost]);
// Clear Inputs
const clear = () => {
setCurrentId(0);
setFormData({ title: "", message: "", image: "" });
};
const handleSubmit = async e => {
e.preventDefault();
if (currentId === 0) {
dispatch(createPost(formData));
clear();
} else {
dispatch(updatePost(currentId, formData));
clear();
}
};
return (
<Wrapper>
<FormContainer onSubmit={handleSubmit}>
<Data>
<DataInput
name="title"
maxLength="50"
placeholder="Title"
type="text"
value={formData.title}
onChange={e => setFormData({ ...formData, title: e.target.value })}
/>
<SecondDataInput
name="message"
placeholder="Message"
maxLength="300"
value={formData.message}
required
onChange={e =>
setFormData({ ...formData, message: e.target.value })
}
/>
<FormContainerImg>
<Filebase
required
type="file"
multiple={false}
onDone={({ base64 }) =>
setFormData({ ...formData, image: base64 })
}
/>
</FormContainerImg>
<FormContainerButtons>
<Buttons type="submit" create>
{specificPost ? "Edit" : "Create"}
</Buttons>
<Buttons onClick={clear} clear>
Clear
</Buttons>
</FormContainerButtons>
</Data>
</FormContainer>
</Wrapper>
);
};
export default Form;
My actions
import {
GETPOSTS,
CREATEPOST,
DELETEPOST,
UPDATEPOST,
LIKEPOST
} from "../actionTypes/posts.js";
import * as api from "../api/posts.js";
export const getPosts = () => async dispatch => {
try {
const { data } = await api.getPosts();
dispatch({ type: GETPOSTS, payload: data });
} catch (error) {
console.log(error);
}
};
export const createPost = newPost => async dispatch => {
try {
const { data } = await api.createPost(newPost);
dispatch({ type: CREATEPOST, payload: data });
} catch (error) {
console.log(error);
}
};
export const updatePost = (id, updatePost) => async dispatch => {
try {
const { data } = await api.updatePost(id, updatePost);
dispatch({ type: UPDATEPOST, payload: data });
} catch (error) {
console.log(error);
}
};
export const deletePost = id => async dispatch => {
try {
await api.deletePost(id);
dispatch({ type: DELETEPOST, payload: id });
} catch (error) {
console.log(error);
}
};
Redux Part
import {
GETPOSTS,
CREATEPOST,
DELETEPOST,
UPDATEPOST,
LIKEPOST
} from "../actionTypes/posts.js";
const postData = (posts = [], action) => {
switch (action.type) {
case GETPOSTS:
return action.payload;
case CREATEPOST:
return [...posts, action.payload];
case UPDATEPOST:
return posts.map(post =>
action.payload._id === post._id ? action.payload : posts
);
case DELETEPOST:
return posts.filter(post => post._id !== action.payload);
default:
return posts;
}
};
export default postData;
My controllers in the backend
import mongoose from "mongoose";
import infoPost from "../models/posts.js";
// Getting All The Posts
export const getPosts = async (req, res) => {
try {
const Posts = await infoPost.find();
res.status(200).json(Posts);
} catch (error) {
res.status(404).json({ message: error.message });
console.log(error);
}
};
// Creating A Post
export const createPost = async (req, res) => {
const { title, message, image } = req.body;
const newPost = new infoPost({ title, message, image });
try {
await newPost.save();
res.status(201).json(newPost);
} catch (error) {
res.status(409).json({ message: error.message });
console.log(error);
}
};
// Update A Post
export const updatePost = async (req, res) => {
const { id } = req.params;
const { title, message, image } = req.body;
if (!mongoose.Types.ObjectId.isValid(id))
return res.status(404).send(`No Post With Id Of ${id}`);
const updatedPost = { title, message, image, _id: id };
await infoPost.findByIdAndUpdate(id, updatedPost, { new: true });
res.json(updatedPost);
};
// Deleting A Post
export const deletePost = async (req, res) => {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id))
return res
.status(404)
.send(`We Couldnt Found The Post With Id Of ${id} To Delete`);
await infoPost.findByIdAndRemove(id);
res.json(`Post With Id Of ${id} Deleted Succesfully`);
};
// Liking A Post
export const likePost = async (req, res) => {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id))
return res.status(404).send(`No post with id: ${id}`);
const post = await infoPost.findById(id);
const updatedPost = await infoPost.findByIdAndUpdate(
id,
{ likeCount: post.likeCount + 1 },
{ new: true }
);
res.json(updatedPost);
};
Even though i've been trying to solve this problem for nearly 3.5 hours, i think that the problem might be in my Posts.js part, if you can help me, you're the greatest !

Resources