Reputation: 149
I currently have a react page that displays a List of orders for the user that is logged in (see UserWelcome below) this page works as I want it to. I now want to make the list of order numbers found in the map / list, clickable and load a new page (OrderDetails as seen below). But I don't know how to pass the OrderNumber from the map to the OrderDetails page so I can use it in my api search. Can anybody tell me how this is done please?
import React from "react";
import { Link } from 'react-router-dom';
class UserWelcome extends React.Component {
constructor(props){
super(props);
this.state = {
data: [],
isLoading: false,
};
}
componentDidMount(){
this.setState({ isLoading: true });
const serachByUserId = this.props.location.state;
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "my web api" + serachByUserId;
fetch(proxyurl + url)
.then(res => res.json())
.then(data => this.setState({ data: data, isLoading: false }));
};
render() {
const { data, isLoading } = this.state;
if (isLoading) {
return <p>Loading ...</p>;
};
if (data.length === 0){
return <p> no data found</p>
}
console.log('data =', data)
return (
<div>
<p> UserID = {data.UserId}</p>
<p> Welcome back {data.UserName}</p>
<p> Below you can find a list of your Orders, link each order to view more details:</p>
<ul>
{data.orders.map(order=>
<li><Link to={{ pathname: "/OderDetails"}}>Order number: {order.orderNumber}</Link></li>
)}
</ul>
</div>
);
}
}
export default UserWelcome;
import React from 'react';
class OrderDetails extends React.Component {
constructor(props){
super(props);
const { data } = props.location
this.state = {
isLoading: false,
};
}
componentDidMount(){
this.setState({ isLoading: true });
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "my wbi api url" + DATA PASSED INTO THE COMPONANT?;
fetch(proxyurl + url)
.then(res => res.json())
.then(data => this.setState({ data: data, isLoading: false }));
};
render() {
const { data, isLoading } = this.state;
if (isLoading) {
return <p>Loading ...</p>;
};
if (data.length === 0){
return <p> no data found</p>
}
return (
<ul>
<p> Order Number XXX(from what has been passed in from other componant)</p>
<p> then i will use this section to log the data from the web api</p>
</ul>
);
}
}
export default OrderDetails;
Upvotes: 0
Views: 30
Reputation: 333
I would do it like that
{data.orders.map(({orderNumber}) =>
<li><Link to={{ pathname: "/OderDetails", orderNumber}}>Order number: {orderNumber}</Link></li>
)}
And then
this.props.location.orderNumber
Upvotes: 0
Reputation: 1517
you can pass it through link and do it like:
<li><Link to={{ pathname: "/OderDetails", state: {orderNumber: orderNumber}}>Order number: {order.orderNumber}</Link></li>
)}
and access it on OrderDetaile component like:
props.location.state.orderNumber
Upvotes: 1