code
import React, { useEffect, useState } from "react";
import "./main.css"
import { AiOutlineCheck, AiOutlineClose, AiOutlineArrowUp, AiOutlineArrowDown } from "react-icons/ai";
import axios from "axios";
const Header = () => {
const [setdata, fetchdata] = useState([]);
const [setpostData, Postdata] = useState([]);
useEffect(() => {
getfetchData();
}, [])
useEffect(() => {
setdata.forEach(function (val) {
getPostData(val.Player, val.IP, val.Port, val.ChannelName);
});
}, [setdata]);
function getfetchData() {
axios.get("http://localhost:9763/api/getPlayers",
{
headers: {
"accepts": "application/json",
'Access-Control-Allow-Origin': '*',
},
auth: {
username: 'admin',
password: 'password'
},
}).then(response => {
//console.log(response.data)
//console.log([...Object.values(response.data).flat()]);
fetchdata([...Object.values(response.data).flat()]);
}).catch(error => {
console.log(error);
});
}
var temp = [];
// Post Data
function getPostData(Player, IP, Port, channelName) {
var data = {
PlayerName: Player,
ChannelName: channelName,
Port: Port,
IpAddress: IP
}
axios({
method: 'post',
url: 'http://localhost:9763/api/getPlayerStatus',
data,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
auth: {
username: 'admin',
password: 'password'
}
}).then(response => {
var tempObj;
tempObj = [response.data];
for (var i = 0; i <= tempObj.length; i++) {
if (tempObj[i] !== undefined) {
temp.push(tempObj[i]);
}
}
Postdata(temp);
}).catch(error => {
console.log("Error In Post Data", error);
});
}
console.log("set", setpostData);
return (
<div className="container-fluid pt-2">
<table className=" table-borderless text-center" id="refresh">
<thead>
<tr className="title" >
{
Object.values(setdata).map((val) => {
return (
<th key={val.Player} > <AiOutlineCheck style={{ color: 'black', backgroundColor: "#41fc00", borderRadius: "25px" }} />
{val.ChannelName} </th>
)
})
}
</tr>
</thead>
<tbody>
<tr >
{
setpostData.map((val, index) => {
// console.log("Inside Map", val);
return (
<td key={index}>{val.Properties.Upcounter} </td>
)
})
}
</tr>
<tr>
{
setpostData.map((val, index) => {
// console.log("Inside Map", val);
return (
<td key={index}>{val.Properties.DownCounter} </td>
)
})
}</tr>
</tbody>
</table>
</div >
);
}
export default Header;
not able to map the table row only first fetch data is visible in data row i have 4 data in fetch
Console Image
and why 2 set In console is fetch? please help me i want to store the fetch data in temp and then display in table row for setInterval
Please provide code
first, I fetch channels 1,2,3,4 from get method and then call post data in which I call function parameter and check the get method data in the body parameter of post method and print the data of post method but it is in the form of object in the console and I want to store in temp and them display it in the web page
It looks like you might need to parse the returned value before trying to map over it.
The returned value is JSON, not JS.
JSON.parse(response.data)
Related
I am handling selected users id using checkbox in the table but when i send request to server to delete them all , i have no idea how to handle with nodejs using mongoose. Can anyone help me?
Here is FE code:
const Home =()=> {
const [isChecked, setisChecked] = useState([]);
const handleDeleteUser = async () => {
const response = await fetch(`http://localhost:3001/users/deleteUsers`, {
method: "DELETE",
body: JSON.stringify(isChecked),
headers: {
"Content-Type": "application/json",
},
});
};
const handlecheckbox = (e) => {
const { value, checked } = e.target;
console.log(value);
if (checked) {
setisChecked([...isChecked, value]);
} else {
setisChecked(isChecked.filter((e) => e !== value));
}
};
return (
<tbody>
{users.map((user) => (
<tr key={user._id}>
<td>
<Form.Group>
<Form.Check
type="checkbox"
value={user._id}
checked={user.isChecked}
onChange={(e) => handlecheckbox(e)}
/>
</Form.Group>
</td>
<td>{user._id}</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.lastLogin}</td>
<td>{user.createdAt}</td>
<td>{user.status}</td>
</tr>
))}
</tbody>
)
}
Here Nodejs code :
userRouter.delete('/deleteUsers', async(req,res,next)=> {
try {
const selectedUsers = req.body
} catch (error) {
next(error)
}
})
Assuming selectedUsers in the route is an array of ids, the following line should do the trick, if you want to do hard-delete.
await User.deleteMany({ _id: { $in: selectedUsers } });
More commonly, people want to do soft-delete where they define an isDeleted property on the schema as a Boolean, and then do the following:
await User.updateMany({ _id: { $in: selectedUsers } }, { isDeleted: true });
I am trying to delete a specific to-do item using the to-do's id. I am, however, experiencing the following error:
DELETE http://localhost:3000/users/todo/delete/undefined 404 (Not Found)
Please see below:
My code is as follows:
- GetToDoList:
import React, { useState, useEffect } from "react";
import axios from "axios";
import moment from "moment";
import DeleteToDo from "./DeleteToDo";
const TodoList = ({ data }) => {
const { Date, Todo, Due } = data;
return (
<tr>
<td>{moment(Date).format("L")}</td>
<td className="todotext">{Todo}</td>
<td>{moment(Due).format("L")}</td>
<td className="tdactions">
<DeleteToDo />
</td>
</tr>
);
};
const GetToDoList = () => {
const [todos, setTodos] = useState([]);
useEffect(() => {
axios({
url: "/todos/gettodo",
method: "get",
headers: {
"Content-type": "application/json",
},
})
.then((res) => {
const data = res.data;
console.log("data:", data);
setTodos(data.todos);
})
.catch((err) => console.log(err));
}, []);
return (
<div>
<header>
<h1>To Do List</h1>
</header>
<table>
<thead>
<tr>
<th className="thdate">CREATED:</th>
<th id="thtodo">TO-DO:</th>
<th className="thdate">DUE:</th>
</tr>
</thead>
<tbody>
{todos && todos.length >= 0
? todos.map((todo, _id) => <TodoList data={todo} key={_id} />)
: null}
</tbody>
</table>
</div>
);
};
export default GetToDoList;
- DeleteToDo:
import React, { useState } from "react";
import axios from "axios";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { faTrashAlt } from "#fortawesome/free-solid-svg-icons";
import Swal from "sweetalert2";
const DeleteToDo = ({ _id }) => {
const [todos, setTodos] = useState([]);
const remove = (e, _id) => {
e.preventDefault();
axios
.delete(`todo/delete/${_id}`) //Have to send the JWT back to the Server, send via headers
.then((response) => {
const del = todos.filter((todo) => _id !== todo._id);
setTodos(del);
console.log("response", response);
Swal.fire({
icon: "success",
confirmButtonColor: "#000000",
timer: 3000,
width: 400,
title: "SUCCESS!",
text: response.data.message,
}).then(function () {
window.location.reload();
});
})
.catch((error) => {
Swal.fire({
icon: "error",
confirmButtonColor: "#ff0000",
width: 400,
title: "ERROR!",
text: error.response.data.message,
}).then(function () {
window.location.reload();
});
});
};
return (
<div>
<td className="tdactions">
<FontAwesomeIcon
icon={faTrashAlt}
onClick={(e) => remove(e, _id)}
id="removebutton"
title="Remove"
/>
</td>
</div>
);
};
export default DeleteToDo;
- TodoControllers:
const Todo = require("../models/todoModels.js");
const mongoose = require("mongoose");
exports.createController = (req, res) => {
let todo = new Todo({
Todo: req.body.Todo,
Date: req.body.Date,
Due: req.body.Due,
});
todo
.save()
.then((todos) => {
return res.json({ message: "Todo created successfully.", todos });
})
.catch((err) => {
return res.status(400).json({ message: "Error creating the todo.", err });
});
};
exports.getAllTodosController = (req, res, next) => {
Todo.find({})
.then((todos) => {
return res.json({ secret: "resource", todos });
})
.catch((err) => {
return res
.status(400)
.json({ message: "Error getting the todos' information.", err });
});
};
exports.removeOneController = (req, res) => {
Todo.findByIdAndRemove(req.params.id)
.then((todos) => {
return res.json({ message: "Todo deleted successfully.", todos });
})
.catch((err) => {
return res
.status(400)
.json({ message: "Error deleting the todo item.", err });
});
};
I am using the id as the unique key prop of the todos in order to delete that particular list item.
Please may someone assist?
A lot of thanks to Shyam, as he has helped me tremendously sorting this out.
As he has mentioned, I wasn't passing the _id to the "DeleteToDo" component. I needed to add it as follows:
<DeleteToDo _id={_id}/>
It was also drawing from localhost:3000/users/todo/delete/612dc2e3e0338ed3fcd7004f instead of localhost:3000/todo/delete/612dc2e3e0338ed3fcd7004f.
After changes to the DeleteToDo component and routing, all seems to be in order.
I have develope application in reactjs and nodejs with postgresql database, when i call api using axios from AxiosTable.js file data from table is fetched successfully and displayed in console but when i try to display in table it doesnot work, so tell me what i do wrong here?
server.js
var restify=require('restify')
const {empdetails} = require('./Function');
var server=restify.createServer() //server created
server.get('/empdetails',empdetails)
server.listen(8080, function(){
console.log("server started...")
})
AxiosTable.js
import React, { Component } from 'react'
import axios from 'axios'
export class AxiosTable extends Component {
state={
persons:[]
}
componentDidMount(){
axios.get('http://localhost:8080/empdetails')
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}
render() {
return (
<div className="App">
<div className="left">
<table className="table table-hover table-dark">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
{ this.state.persons.map(person =>
<tr>
<td>{person.id}</td>
<td>{person.name}</td>
<td>{person.email}</td>
</tr>
)}
</table>
</div> </div>
)
}
}
export default AxiosTable
Function.js //backend code
var Sequelize=require('sequelize')
const connection = new Sequelize('mydb', 'postgres', 'password', {
host: 'localhost',
dialect: 'postgres'
});
var Demo=connection.define('demo',{
name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
}
})
module.exports ={
// employee details fetched
empdetails: function empdetails(req,res,next){
res.send('employee details ')
connection.sync().then(function(){
Demo.findAll().then(function(demos){
console.log(demos)
})
})
},
};
Try this
componentDidMount(){
axios.get('http://localhost:8080/empdetails')
.then(res => {
const persons = res.data;
this.setState(prevState => { persons: [...prevState.persons, persons] });
})
}
Your backend is not actually returning any data, it looks like.
Try something like
function empdetails(req, res, next) {
connection.sync().then(() => {
Demo.findAll().then((demos) => {
console.log(demos);
res.send(demos); // <-- This is the important bit! :)
});
});
}
instead.
I am making the clone of instagram. In the following code , the span tag is not printing the name of the user who has commented on the post ,. I have checked the record by consoling the result , record is having the name and all the data required . The record.text is working properly and is showing the text but I also want to show the name of the person who commented and it is not working .
{
item.comments.map(record=>{
return(
<h6 key={record._id}><span style={{fontWeight:"500"}}>{record.postedBy.name}</span> {record.text}</h6>
)
})
}
Following file is in main concern:-
Home.js :-
import React, { useState, useEffect, useContext } from 'react';
import { UserContext } from '../../App';
const Home = () => {
const [data, setData] = useState([])
const { state, dispatch } = useContext(UserContext)
useEffect(() => {
fetch('/allpost', {
headers: {
"Authorization": "Bearer " + localStorage.getItem("jwt")
}
}).then(res => res.json())
.then(result => {
console.log(result)
setData(result.posts)
})
}, [])
const likePost = (id) => {
fetch('/like', {
method: "put",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + localStorage.getItem("jwt")
},
body: JSON.stringify({
postId: id
})
}).then(res => res.json())
.then(result => {
//console.log(result)
const newData = data.map(item => {
if (item._id == result._id) {
return result
} else {
return item
}
})
setData(newData)
}).catch(err => {
console.log(err)
})
}
const unlikePost = (id) => {
fetch('/unlike', {
method: "put",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + localStorage.getItem("jwt")
},
body: JSON.stringify({
postId: id
})
}).then(res => res.json())
.then(result => {
//console.log(result)
const newData = data.map(item => {
if (item._id == result._id) {
return result
} else {
return item
}
})
setData(newData)
}).catch(err => {
console.log(err)
})
}
const makeComment = (text, postId) => {
fetch('/comment', {
method: "put",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + localStorage.getItem("jwt")
},
body: JSON.stringify({
postId,
text
})
}).then(res => res.json())
.then(result => {
console.log(result)
const newData = data.map(item => {
if (item._id == result._id) {
return result
} else {
return item
}
})
setData(newData)
}).catch(err => {
console.log(err)
})
}
return (
<div className="home">
{
data.map(item => {
return (
<div className="card home-card">
<h5>{item.postedBy.name}</h5>
<div className="card-image">
<img src={item.photo} />
<div className="card-content">
{item.likes.includes(state._id)
?
<i className="material-icons"
onClick={() => { unlikePost(item._id) }}>
thumb_down
</i>
:
<i className="material-icons"
onClick={() => { likePost(item._id) }}>
thumb_up
</i>
}
<i className="material-icons" style={{ color: "Red" }}>favorite</i>
<h6>
{item.likes.length} likes
</h6>
<h6>
{item.title}
</h6>
<p>{item.body}</p>
{
item.comments.map(record=>{
return(
<h6 key={record._id}><span style={{fontWeight:"500"}}>{record.postedBy.name}</span> {record.text}</h6>
)
})
}
<form onSubmit={(e) => {
e.preventDefault()
// console.log(e.target[0].value)
makeComment(e.target[0].value, item._id)
}}>
<input type="text" placeholder="add a comment" />
</form>
</div>
</div>
</div>
)
})
}
</div>
)
}
export default Home
so I'm making a mini eCommerce app using MERN stack, i'm fetching products for each seller using his id, so he's the only one who can edit or delete his own products,
in my component i get the user's id from redux state from the user, then i use the id to fetch products for each logged in seller.(in useEffect)
so fetching products depends on the user, and the user is always loaded and no need to fetch it after he login.
the problem is, only the first time after i login and i render the component it gives me
TypeError: products.map is not a function. but if i refresh the page it works fine
so it doesn't see products the first time idk why even if the user is there and the id to fireup the fetching function.
function EditProducts() {
const { user } = useSelector(state => state.userrr);
const { loading, products } = useSelector(state => state.userProductsss);
const dispatch = useDispatch();
useEffect(() => {
console.log(user);
console.log(products);
if (!user) {
return;
} else {
let id = user._id;
dispatch(fetchUserProducts(id));
}
}, [dispatch, user]);
const deleteIt = id => {
dispatch(deleteProduct(id))
.then(res => {
toast.success(res, { position: toast.POSITION.BOTTOM_LEFT });
})
.catch(error => {
toast.error(error, {
position: toast.POSITION.BOTTOM_LEFT,
autoClose: false
});
});
};
console.log(products);
return (
<Container>
<Table striped bordered hover variant='dark'>
<thead>
<tr>
<th>category</th>
<th>Description</th>
<th>Price</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
{loading && (
<tr>
<td colSpan='4'>
<Spinner animation='border' /> loading...{" "}
</td>
</tr>
)}
{!user && !loading && (
<tr>
<td colSpan='4'>Please Log in to access this page</td>
</tr>
)}
{products.map(product => (
<tr key={product._id}>
<td>{product.name}</td>
<td>{product.description}</td>
<td>${product.price}</td>
<td>
<span className='btn btn-primary mr-3'>
<UpdateProductForm
id={product._id}
name={product.name}
description={product.description}
category={product.category}
price={product.price}
numberInStock={product.numberInStock}
productImage={product.productImage}
/>
</span>
<Button className='btn btn-danger' onClick={() => deleteIt(product._id)}>
<FontAwesomeIcon icon={faTrash} />
</Button>
</td>
</tr>
))}
</tbody>
</Table>
</Container>
);
}
export default EditProducts;
this is my reducer
const productReducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_USER_PRODUCTS_STARTED:
return {
...state,
loading: true
};
case FETCH_USER_PRODUCTS_SUCCESS:
return {
...state,
loading: false,
error: null,
products: action.payload.products
};
case FETCH_USER_PRODUCTS_FAILURE:
return {
...state,
loading: false,
error: action.payload.error,
success: null
};
default:
return state;
}
};
this is the actions
export const fetchUserProducts = userId => {
return dispatch => {
dispatch(fetchUserProductsStarted());
axios
.get(`/api/product/${userId}/products`)
.then(res => {
dispatch(fetchUserProductsSuccess(res.data));
})
.catch(error => {
dispatch(fetchUserProductsFailure(error.message));
});
};
};
const fetchUserProductsStarted = () => {
return {
type: FETCH_USER_PRODUCTS_STARTED
};
};
const fetchUserProductsSuccess = products => {
return {
type: FETCH_USER_PRODUCTS_SUCCESS,
payload: {
products
}
};
};
const fetchUserProductsFailure = error => {
return {
type: FETCH_USER_PRODUCTS_FAILURE,
payload: {
error
}
};
};
so the problem was that useEffect couldn't be able to ensure the user data is loaded before the first render here:
const { user } = useSelector(state => state.userrr);
so the user was null, so it couldn't get the products depending on the user id.
what i did is that i loaded the user again inside the component useEffect so it gets the user data.
useEffect(() => {
dispatch(loadUser());
const id = user ? user._id : null;
dispatch(fetchUserProducts(id));
}, [ dispatch, id]);