Delete an item with ReactJS - node.js

I'm trying to delete an item after the user clicks on the Delete button. Through the handleDelete function, I am passing an id (idBooks) via axios when the user clicks a book. How do I withdraw it from the click?
Below you will find the React code and then the backend side code in node js.
Frontend
(class extends React.Component {
handleDelete = (e) => {
e.preventDefault();
const { book } = this.props;
axios.delete("http://localhost:8081/delete", book.idBooks )
.then(res => {
console.log(res.data);
}).catch(err => {
console.warn(err.warn);
});
};
render() {
const { book, classes } = this.props;
const token = localStorage.getItem('token');
return(
<Paper className= { classes.marginTopBottom }>
<h2 className={ classes.title }>
{ book.title }
</h2><hr />
<div className= { classes.scrollingDiv }>
<p>
{ book.plot }
</p>
</div>
<hr/>
<div className={ classes.pStyle }>
<p>Publish date:<br /> { new Date(book.publish_date).toLocaleDateString() }</p>
<p>Author:<br /> { book.author }
</p>
<p>Genre:<br /> { book.genre }</p>
</div>
<div>
{ token && (
<Button className={ classes.delete } size="small" onClick={this.handleDelete} type="button" variant="contained" color="primary"
component= {Link} to="delete">
Delete
<DeleteIcon className={ classes.rightIcon } />
</Button>
)}
</div>
</Paper>
)
}
});
Backend
const deleteBook = (req, res) => {
const connection = mysql.createConnection(connectionProperties);
connection.connect();
const query = `DELETE FROM Books WHERE idBooks = ${ req.body.idBooks }`;
connection.query(query, (err, res) => {
if (err) {
res.status(500).send(err);
} else {
res.status(200).send('Book deleted correctly.');
}
});
};

I'd add a prop onDeleteCallback, and on successful delete call that function with deleted book id. In parent component (with all the books are listed) update the state with filtered out books.

I guess passing the parameter might help you fix this issue.
On the delete Button add a parameter to the onClick={()=>this.handleDelete(e,book.idBooks)}
Change the handleDelete function a bit as below
handleDelete = (e,idBooks) => {
e.preventDefault();
axios.delete("http://localhost:8081/delete", idBooks )
.then(res => {
console.log(res.data);
}).catch(err => {
console.warn(err.warn);
});
};

Related

How to get the object id after the button click in Reactjs

I am working in MERN project.
what I want
I am fetching the project list from the backend If i click on any project it should give the members list that is working on that project so i want to get the objectid of that clicked project
what i tried
import React, { useState, useEffect } from 'react'
import { NavLink } from 'react-router-dom'
import { useNavigate } from 'react-router-dom';
const AdminDash = () => {
const navigate = useNavigate()
const [userData, setuserData] = useState([])
const [data, setData] = useState({});
const callAboutPage = async () => {
try {
const res = await fetch("/alldata", {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
credentials: "include"
})
const data = await res.json()
setuserData(data)
console.log(setuserData);
if (!res.status === 200) {
const error = new Error(res.error)
throw error
}
} catch (error) {
console.log(error);
navigate("/")
}
}
function handleButtonClick(id) {
fetch(`/api/get-data/${id}`)
.then(response => response.json())
.then(data => {
setData(data);
console.log(data);
});
}
useEffect(() => {
callAboutPage()
}, [])
return (
<>
<div className='container mt-5'>
<div className='row'>
<div className='col-sm-10 col-md-10 col-lg-10'>
<div class="row align-items-md-stretch">
<div class="col-md-6">
<div class="h-100 p-5 text-bg-light rounded-3">
<h2>Current Ongoing Projects</h2>
<ol class="list-group list-group-numbered mt-5">
{
userData.map((item, i) => (
<li class="list-group-item d-flex justify-content-between align-items-start">
<div class="ms-2 me-auto">
<NavLink onClick={() => handleButtonClick()} to="/admindash" className="text-decoration-none"><div class="fw-bold">{item.name}</div></NavLink>
Content for list item
</div>
<i class="bi bi-at"></i>
</li>
))}
</ol>
<label>{data.name}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</>
)
}
export default AdminDash
backend
app.get('/api/get-data/:id', (req, res) => {
ProjectSchema.findById(req.params.id, (err, doc) => {
if (err) {
res.send(err);
} else {
res.json(doc);
}
});
});
the output i get in my console
{stringValue: '"undefined"', valueType: 'string', kind: 'ObjectId', value: 'undefined', path: '_id', …}
How to achieve this ..any suggestions?
In the mapping onClick pass item.id.
First make sure you getting it in your data while Fetching.
<NavLink onClick={() => handleButtonClick(item.id)} to="/admindash" className="text-decoration-none">{item.name}

Unable to use the server side props in Next JS while using the axios as middleware in the React Context

I would like to get the request using the status side props in Next JS, however, I'm receiving an error that status code is not defines which I declared in the context api file.
This is from my client side next js page
function Instructor({ courses }) {
const router = useRouter();
const { Meta } = Card;
return (
<div className="overflow-hidden">
<InstructorRoute>
<h1 className="jumbotron square">This is Instructor Dashboard</h1>
<div class="row">
{courses &&
courses.map((course, index) => {
return (
<div class="col-sm-4 scaling">
<Badge.Ribbon
text={course.published ? "Published" : "Draft"}
color={course.published ? "green" : "gold"}
>
<div class="card">
<div class="card-body">
<Link href={`/instructor/course/view/${course.slug}`}>
<a className="card-title text-black fw-bold">
<ReactMarkdown> {course.name}</ReactMarkdown>
</a>
</Link>
<p class="card-text text-truncate">
{course.description}
</p>
<img
style={{ cursor: "pointer" }}
onClick={(e) => {
e.preventDefault();
router.push(
`/instructor/course/view/${course.slug}`
);
}}
class="card-img-bottom "
height="200px"
src={
course.image ? course.image.Location : "/course.png"
}
alt="Card image cap"
/>
<hr className="fullWidth" />
<p class="mt-2 card-text">
<p class=" fs-6 badge bg-warning">
{course.lessons.length} Lessons
</p>
</p>
</div>
</div>
</Badge.Ribbon>
</div>
);
})}
</div>
</InstructorRoute>
</div>
);
}
export async function getStaticProps(context) {
const { data } = await axios.get("/api/instructor-courses");
// setCourses(data);
console.log(data);
return {
props: {
courses: data,
},
};
}
export default Instructor;
This is from my context api page:
function Provider({ children }) {
const router = useRouter();
const [state, dispatch] = useReducer(rootReducer, initialState);
useEffect(() => {
dispatch({
type: "LOGIN",
payload: JSON.parse(window.localStorage.getItem("user")),
});
}, []);
axios.interceptors.response.use(
(response) => {
return response;
},
(err) => {
let res = err.response;
console.log(res);
if (res.status === 401 && res.config && !res.config.__isRetryRequest) {
return new Promise((resolve, reject) => {
axios
.get("api/logout")
.then((data) => {
console.log("401 error > logout");
dispatch({ type: "LOGOUT" });
window.localStorage.removeItem("user");
router.push("/login");
})
.catch((err) => {
console.log("Error", err);
reject(err);
});
});
}
return Promise.reject(err);
}
);
useEffect(() => {
async function getCsrfToken() {
const { data } = await axios.get("/api/csrf-token");
console.log("CSRF", data);
axios.defaults.headers["X-CSRF-Token"] = data.getCsrfToken;
}
getCsrfToken();
}, []);
return (
<Context.Provider value={{ state, dispatch }}>{children}</Context.Provider>
);
}
export { Context, Provider };
This is my app.js page:
function MyApp({ Component, pageProps }) {
return (
<Provider>
<Nav></Nav>
<ToastContainer
theme="colored"
position="top-center"
limit={3}
autoClose={1500}
/>
<Component {...pageProps}></Component>
</Provider>
);
}
This is the error that I'm receiving. However, the code works if I don't use server side rendering or static side rendering
Server Error
TypeError: Cannot read property 'status' of undefined
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
context\index.js (39:14) # eval
37 | let res = err.response;
38 | console.log(res);
> 39 | if (res.status === 401 && res.config && !res.config.__isRetryRequest) {
| ^
40 | return new Promise((resolve, reject) => {
41 | axios
42 | .get("api/logout")

Whenever i send msg it is showing same message multiple times in react

the above img shows the proplem. you can check the console in bottom right too
I am working on one to one chat website using socket io react node,express i am facing this issue where example :when i type first hi then hi displays 1 time when i type hii it gets displayed 2 times when 3rd time i type jo it displays jo 3 times how can i fix this this is my react code Also my messaging is not receiving at other end it is displaying only on senders page
import React, { Component } from 'react';
import { Link,Redirect } from 'react-router-dom';
import UserService from "../services/userservice";
import {getUsersFriend} from "../services/messageservice";
import io from "socket.io-client";
const SOCKET_IO_URL = "http://localhost:4000/";
export default class Messages extends Component {
constructor(props){
super(props)
this.socket = io(SOCKET_IO_URL)
this.state = {
currentUser: UserService.getCurrentUser(),
isLoading:false,
userdetails:[],
show:false,
username:'',
message:'',
socketConnected:false,
messages:[]
};
this.onTextboxChangeMessage = this.onTextboxChangeMessage.bind(this)
}
componentDidMount(){
const {currentUser}=this.state
this.fetchUser()
this.socket.on('connect',()=> {
this.setState({ socketConnected : true})
// console.log("connection")
})
}
async fetchUser(){
try{
const {currentUser} = this.state
console.log(currentUser)
const data = { userid : currentUser.user._id }
console.log(data)
let user = await getUsersFriend(data)
this.setState({ userdetails: user });
// console.log(user)
}catch(err){
console.log(err)
}
}
showMessageSpace(elementusername){
this.setState({
show: true,
username:elementusername
});
}
onTextboxChangeMessage(e){
this.setState({ message:e.target.value})
}
SendMessage(e,senderid,receiverusername,message,senderusername){
e.preventDefault();
e.stopPropagation()
console.log('event', e)
const {messages} =this.state
if(this.state.socketConnected){
console.log('if condition test',senderid,receiverusername,message,senderusername )
this.socket.emit('send',{senderid,receiverusername,message,senderusername});
this.socket.on(`${receiverusername}`, (d)=>{
if(this.state[`${receiverusername}`]?.length >= 1 ){
let messageList = this.state[`${receiverusername}`]
this.setState({[`${receiverusername}`]:[...messageList,d]})
}
else{
this.setState({[`${receiverusername}`]:[d]})
console.log('else Condition store individual messages', this.state[`${receiverusername}`])
}
}
this.setState( { message:'' })
}
render(){
const { currentUser ,isLoading,userdetails,message,messages} = this.state;
// console.log(messages)
if (isLoading) {
return (<div><p>Loading...</p></div>);
}
if(!currentUser){
return(
<div>
<Redirect to='/login' />
</div>
)
}
else{
return(
<div>
<h1>Messages</h1>
<div>
<p>Users</p>
{' '}
<ul className="collection">
{userdetails.map((element) => {
return(
<div key={element._id}>
<li><Link to={`/dashboard/profile/:${element._id}`}>{element.username}</Link>{' '}<input
type="button"
id={element._id}
value="Message"
onClick={this.showMessageSpace.bind(this,element.username)} ></input></li>
</div>
);
})
}
</ul>
{' '}
</div>
{' '}
<Link to="/dashboard">Dashboard</Link>
{' '}
<div>
{
this.state.show &&
(<div>
<h2>Username : {' '}{this.state.username}</h2>
{' '}
<div>
<h3>Body</h3>
<div>
<ul>
{/* { this.state[`${this.state.username}`]?.map((msg,key) =>{ */}
{this.state.username?.length > 0 && this.state[`${this.state.username}`]?.map((msg,key) =>{
return(<li key={key}>{msg.senderusername}<span>{' '}{msg.message}</span></li>);
})
}
</ul>
</div>
</div>
{' '}
<div>
{' '}
<input
type="text"
name="message"
value={message}
onChange={this.onTextboxChangeMessage}
></input>
<button className='btn btn-info' onClick={(e)=> {this.SendMessage(e,currentUser.user._id,this.state.username,this.state.message,currentUser.user.username)}}>Send</button>
</div>
{' '}
</div>)
}
</div>
</div>
)
}
}
}
server code:
io.on('connection', (socket) => { /* socket object may be used to send specific messages to the new connected client */
console.log('connection established',socket.id);
socket.on('send', (data)=>{
console.log("Receive data from single username",data)
io.emit('message',data)
socket.on('message',data => {
console.log("private")
io.to(data.receiverid).emit('message',data)
})
});
socket.on('disconnected',()=>{
console.log("disconnect")
})
});
This is because you assign another new callback to the socket every time you send a message.
Move this part:
this.socket.on(`${receiverusername}`, (d)=>{
if(this.state[`${receiverusername}`]?.length >= 1 ){
let messageList = this.state[`${receiverusername}`]
this.setState({[`${receiverusername}`]:[...messageList,d]})
} else {
this.setState({[`${receiverusername}`]:[d]})
console.log('else Condition store individual messages',
this.state[`${receiverusername}`])
}
into onconnect callback:
this.socket.on('connect',()=> {
this.setState({ socketConnected : true})
this.socket.on("message", (d)=>{
if(this.state[`${d.receiverusername}`]?.length >= 1 ){
let messageList = this.state[`${d.receiverusername}`]
this.setState({[`${receiverusername}`]:[...messageList,d.content]})
} else {
this.setState({[`${d.receiverusername}`]:[d.content]})
console.log('else Condition store individual messages',
this.state[`${receiverusername}`])
}
})
But in this variant, you don't have receiverusername.
So you should send general "message" event from your server as object containing receiverusername.
The on method is exactly explained in socket.io documentation: https://socket.io/docs/v3/listening-to-events/
And pattern with assigning onmessage callback in the onconnect handler is documented here:
https://socket.io/get-started/chat/#Broadcasting

_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 !

Data fetching from oracle db and displaying on browser using app.get

I am able to fetch the data from the db and it is displaying on the inspect element also but it is not displaying on the browser i mean UI.
//storing the data into the posts
this.state = {
displayMenu: false,
posts: [ ]
};
//click function for the drop down and handling the axios.get
Click = event => {
event.preventDefault();
let currentComponent = this;
axios.get(`http://localhost:4000/api/AMS`)
.then(function (response) {
console.log(response);
currentComponent.setState({posts: response.data})
})
.catch(function (error) {
console.log(error);
});
}
//Render method
render() {
// var back = {backgroundSize : 'cover'};
var textStyle = {
position: 'absolute',
top: '50%',
left: '50%'
};
//From here the checking of data is happening, if the data is found inside the posts it will show it on the browser otherwise it will show no posts.
const { posts } = this.state;
const postList = posts.length ? (
posts.map(post => {
// console.log('hi');
return (
<div className="post card" key={post.ID}>
<div className="card-content">
</div>
</div>
)
})
) : ( <div className="center">No posts yet</div>)
//RETURN method
return (
<div>
{/* <Image
style={back} responsive
src={logo}>
</Image> */}
<div style={textStyle} className="dropdown" style = {{background:"red",width:"200px"}} >
<div className="button" onClick={this.showDropdownMenu}> Regions </div>
{ this.state.displayMenu ? (
<ul>
<li><a className="active" href="/AMS" onClick={this.Click}>AMS</a></li>
<li>EMEA</li>
<li>APJ</li>
</ul>
):(null)
}
</div>
//Here i am calling the postList variable
{postList}
{/* {this.state.posts}<br/>
{this.state.pictures} */}
</div>
);
}
}
Click = event => {
event.preventDefault();
let currentComponent = this;
axios.get(`http://localhost:4000/api/AMS`)
.then(function (response) {
console.log(response);
currentComponent.setState({posts: response.data})
})
.catch(function (error) {
console.log(error);
});
}
render() {
// var back = {backgroundSize : 'cover'};
var textStyle = {
position: 'absolute',
top: '50%',
left: '50%'
};
const { posts } = this.state;
const postList = posts.length ? (
posts.map(post => {
// console.log('hi');
return (
<div className="post card" key={post.ID}>
<div className="card-content">
</div>
</div>
)
})
) : ( <div className="center">No posts yet</div>)
The results that i am getting in the inspect element console is like below:
ID: 229, EMAIL: "anuraguk3#gmail.com", ROLE: "BASE", PASSWORD:"$2b$10$ShTWYAtF8M5JLhEm68JqTuMx7P8x6dtOIkNsGz4wE21LY92xGoDCO"
DOM is rendered before getting server response.So, you need to use async-await in this scenario. For your program:-
Click = async(event) => {
event.preventDefault();
let currentComponent = this;
await axios.get(`http://localhost:4000/api/AMS`)
.then(function (response) {
console.log(response);
currentComponent.setState({posts: response.data})
})
.catch(function (error) {
console.log(error);
});
}

Resources