import React, { Component } from "react";
import axios from "axios";
import "./getForm.css";
class GetData extends Component {
state = { posts: [] };
componentDidMount() {
axios
.get("http://localhost:8888/api/v1/user") //returns promise
.then((response) => {
this.setState({ posts: response.data });
console.log("response:", response.data);
})
.catch((err) => {
console.log("err:", err);
});
}
render() {
return (
<>
<h1>Posts</h1>
<table>
<tbody>
<tr>
<th>id</th>
<th>name</th>
<th>email</th>
<th>mobile</th>
<th>status</th>
</tr>
{this.state.posts.map((post) => {
return (
<tr key={post.id}>
<td>{post.id}</td>
<td> {post.name}</td>
<td> {post.email}</td>
<td> {post.mobile}</td>
<td>
<img src={post.image} />
</td>
</tr>
);
})}
</tbody>
</table>
</>
);
}
}
export default GetData;
You can add routes for your photos into Node.js public folder:
...
app.use('/photos', express.static(__dirname + '/public/photos'));
...
Then return image_url from http://localhost:8888/api/v1/user, the URL can be like http://localhost:8888/api/v1/photos/your_image_name.jpg
In your React:
...
<img style={{width:500, height:500}} src={post.image_url)} />
...
Note: Assuming you have the image URL's on your server response.
The posts state is being mapped before you receive the response from your server on the initial render. You can add a loading state which is set to true initially and after the response.data is set in the posts state, you can set loading to false.
You can then conditionally render the whole component based on this loading state like this.
Here is a link to a working sandbox.
import React, { Component } from "react";
import axios from "axios";
class GetData extends Component {
state = { posts: [], loading: true };
componentDidMount() {
this.fetchUserData();
}
fetchUserData = async () => {
try {
const response = await axios.get("http://localhost:8888/api/v1/user");
this.setState({ posts: response.data, loading: false });
console.log(response.data);
} catch (error) {
this.setState({ loading: false });
console.log(error);
}
};
render() {
if (this.state.loading) {
return "Loading";
}
return (
<>
<h1>Posts</h1>
<table>
<tbody>
<tr>
<th>id</th>
<th>name</th>
<th>email</th>
<th>mobile</th>
<th>status</th>
</tr>
{this.state.posts.map((post) => {
return (
<tr key={post.id}>
<td>{post.id}</td>
<td> {post.name}</td>
<td> {post.email}</td>
<td> {post.mobile}</td>
<td>
<img src={post.image} />
</td>
</tr>
);
})}
</tbody>
</table>
</>
);
}
}
export default GetData;
Related
here i am fetching data from API which is giving me response in "array of objects" i want to store it in the array called products and want to display it on the page.
Here is my code
import React, { useState, useEffect } from "react";
import '../all.css';
import Axios from "axios";
const AllProduct = () => {
const [products, setProducts] = useState([]);
const fetchProducts = async () => {
const { data } = await Axios.get(
"http://localhost:8080/api/QueryAllProducts"
);
console.log(data.response);
setProducts(data.response);
console.log(products);
};
const display = () => {
return (products ?? []).map(product => (
<tr key={product.id}>
<th>{product.id}</th>
<th>{product.name}</th>
<th>{product.area}</th>
<th>{product.ownerName}</th>
<th>{product.cost}</th>
</tr>
) );
}
useEffect(() => {
fetchProducts();
}, []);
return (
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Area</th>
<th>Owner Name</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
{display()}
</tbody>
</table>
</div>
)
}
export default AllProduct;
I have used ReactJS for frontend and NodeJS
here is the screenshot of what i am getting on console
Check that the type of products is array. If it is an object, an error occurs.
I couldn't map the second API response https://api.coingecko.com/api/v3/global with error prompted (read property 'map' of undefined), while the first API is fine.
Whats the issue here?
export default function Home(props) {
const { data } = props.result;
const { global } = props.nextResult;
<table className="table2 table-hover table-dark">
<thead>
<tr>
<th>Markets</th>
</tr>
</thead>
<tbody>
{global.map (gg => (
<tr key={gg.endedicos}>
<td>{gg.markets}</td>
</tr>
))}
</tbody>
</table>
export async function getServerSideProps(context) {
const params = {
order: CoinGecko.ORDER.MARKET_CAP_DESC
};
const [result, nextResult] = await Promise.all([
coinGeckoClient.coins.markets({params}),
coinGeckoClient.global()
]);
return {
props: {
result, nextResult
},
}
}
import React, { Component } from "react";
import axios from "axios";
class DisplyDish extends Component {
state = { posts: [] };
componentDidMount() {
axios
.get("http://localhost:8888/api/v1/dish") //returns promise
.then(response => {
this.setState({ posts: response.data });
console.log("response:", response.data);
})
.catch(err => {
console.log("err:", err);
});
}
render() {
return (
<>
<table>
<tbody>
<tr>
<th>id</th>
<th>title</th>
<th>type</th>
<th>weight</th>
<th>originalPrice</th>
<th>offerPrice</th>
<th>description</th>
<th>quantity</th>
<th>status</th>
<th>rating</th>
<th>image</th>
</tr>
{this.state.posts.map(post => {
return (
<tr key={post.id}>
<td>{post.id}</td>
<td> {post.title}</td>
<td> {post.type}</td>
<td> {post.weight}</td>
<td>{post.originalPrice}</td>
<td>{post.offerPrice}</td>
<td>{post.description}</td>
<td>{post.quantity}</td>
<td>{post.status}</td>
<td>{post.rating}</td>
<td>
<img
src={"http://localhost:8888/api/v1/dish/" + post.image}
alt="image"
/>
</td>
</tr>
);
})}
</tbody>
</table>
</>
);
}
}
export default DisplyDish;
and this is what i'm getting in console
id: 3
image: "uploads/dish/image_1581159803092.jpg"
I cannot figure out what I am doing wrong here.
I am using the MERN stack and using Axios for HTTP requests. Ideally I would like to have a modal pop-up as well to confirm the deletion but just solving the delete function is driving me crazy. I am new to the MERN stack and it seems overly complicated for some of the simple tasks I am trying to accomplish. Any input helps, thanks in advance.
GitHub Link
My API is working in Postman:
workorderRoutes.route("/:id").delete(function(req, res) {
WorkOrder.findById(req.params.id)
.then(workorder => workorder.remove().then(() => res.json({ success: true })))
.catch(err => res.status(404).json({ success: false }));
});
Below is the component I'm using:
import React, { Component } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
const WorkOrder = props => (
<tr>
<td className={props.workorder.workorder_completed ? "completed" : ""}>{props.workorder.workorder_po}</td>
<td className={props.workorder.workorder_completed ? "completed" : ""}>{props.workorder.workorder_name}</td>
<td className={props.workorder.workorder_completed ? "completed" : ""}>{props.workorder.workorder_status}</td>
<td className={props.workorder.workorder_completed ? "completed" : ""}>{props.workorder.workorder_shippingFrom}</td>
<td className={props.workorder.workorder_completed ? "completed" : ""}>{props.workorder.workorder_completionDate}</td>
<td>
<Link className="btn btn-sm btn-primary" to={"/edit/" + props.workorder._id}>
Edit
</Link>
<button className="btn btn-sm btn-danger" to={"/" + props.workorder._id}>
Remove
</button>
<a className={props.workorder.workorder_completed ? "btn btn-sm btn-info" : "invisible"} href={"https://tools.usps.com/go/TrackConfirmAction?tRef=fullpage&tLc=2&text28777=&tLabels=" + props.workorder.workorder_tracking + "%2C"} target="_blank">
Tracking
</a>
</td>
</tr>
);
export default class WorkOrdersList extends Component {
constructor(props) {
super(props);
this.state = { workorders: [] };
}
componentDidMount() {
axios
.get("http://matthicksdev.com:4000/workorders/")
.then(response => {
this.setState({ workorders: response.data });
})
.catch(function(error) {
console.log(error);
});
}
componentDidUpdate() {
axios
.get("http://matthicksdev.com:4000/workorders/")
.then(response => {
this.setState({ workorders: response.data });
})
.catch(function(error) {
console.log(error);
});
}
workorderList() {
return this.state.workorders.map(function(currentWorkOrder, i) {
return <WorkOrder workorder={currentWorkOrder} key={i} />;
});
}
render() {
return (
<div>
<h3>Work Order Status List</h3>
<table className="table table-sm table-striped table-dark" style={{ marginTop: 20 }}>
<thead>
<tr>
<th>Job ID</th>
<th>Name</th>
<th>Status</th>
<th>Shipping From</th>
<th>Completion/Ship Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>{this.workorderList()}</tbody>
</table>
</div>
);
}
}
For the life of me I can't seem to figure out how to make the entries delete from the MongoDB.
Im trying to build a mini forum for a school project.
Im trying to achieve, when im clicking on the link which in this case in under "Title: Test Post 1" i want to go the post and only show the data, which had the same id.
The routes are working when you click the link it goes to the id, it just shows all the data.
Im having a issue with data, it is showing all "posts" instead of the post with the matching ID.
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
const Post = props => (
<tr>
<td>{props.post.post_vote}</td>
<td>{props.post.post_title}</td>
<td>{props.post.post_question}</td>
<td>{props.post.post_name}</td>
<td>{props.post._id}</td>
</tr>
)
export default class ThePost extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
componentDidMount() {
axios.get('http://localhost:8000/posts/')
.then(response => {
this.setState({posts: response.data})
})
.catch(function (error) {
console.log(error);
})
}
postPost() {
return this.state.posts.map(function(currentPost, i) {
return <Post post={currentPost} key={i} />;
});
}
render() {
return (
<div>
<h3>Question:</h3>
<table className="table table-striped" style={{ marginTop: 20 }}>
<thead>
<tr>
<th>Votes</th>
<th>Title</th>
<th>Question</th>
<th>Name</th>
<th>Id:</th>
</tr>
</thead>
<tbody>
{ this.postPost() }
</tbody>
</table>
<Link to="/"><button className="btn btn-primary">Back to posts</button></Link>
</div>
)
}
}
My app.js
<Switch>
<Route path="/" exact component={PostsList} />
<Route path="/create" component={CreatePost} />
<Route path="/posts/:id" component={ThePost} />
<Route path="/edit/:id" component={EditPost} />
</Switch>
My backend
postRoutes.route('/posts/:id').get(function(req, res) {
let id = req.params.id
Post.findById(id, function(err, post) {
res.json(post);
});
});
I think the problem is here, but im not sure.
postPost() {
return this.state.posts.map(function(currentPost, i) {
return <Post post={currentPost} key={i} />;
});
}
Can anyone help me?
get method with http request need to have id param,
componentDidMount() {
axios.get('http://localhost:8000/posts/'+this.props.match.params.id)
.then(response => {
this.setState({posts: response.data})
})
.catch(function (error) {
console.log(error);
})
}