Reputation: 25
I have a component Active.js, that lists items thought axios get, and then there is a link on name (sub-component ActiveDetails.js) that I wish returns that specific object user clicks on in order to get more details. But it returns an empty object. ID is undefined. console
How link id of object to specific url?
import axios from 'axios';
import moment from 'moment';
import { Link } from 'react-router-dom';
export default class Active extends React.Component {
constructor(props) {
super(props)
this.state = {
activeVisitors: [],
};
}
componentDidMount() {
axios.get('http://localhost:8085/api/visitors/')
.then(res => {
this.setState({ activeVisitors: res.data._embedded.visitorList, });
})
.catch(error => {
console.log(error)
});
}
render() {
return (
<>
<h1>Active visitors</h1>
<div >
<ol>
{this.state.activeVisitors.map(activeVisitor =>
<li key={activeVisitor.id}>
<div>
<div>
<Link to={`/active/${activeVisitor.id}`}>Name: {activeVisitor.name}</Link>
</div> <br/>
<button onClick={this.handleRemoveClick}>Remove</button>
Time: {moment(activeVisitor.dateTime).format('MMMM Do YYYY, h:mm:ss a')}<br />
</div></li>)}
</ol>
</div>
</>
);
}
}
import React from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
export default class VisitorDetails extends React.Component {
constructor(props) {
super(props)
this.state = {
visitors: {},
};
}
componentDidMount() {
axios.get(`http://localhost:8085/api/visitors/${this.state.id}`)
.then(res => {
this.setState({ visitors: res.data._embedded.visitorList });
})
.catch(error => {
console.log(error)
});
}
render() {
return (
<>
<div className='item'>
{this.state.visitors.id}
Name: {this.state.visitors.name}
Badge Nr: {this.state.visitors.accessCardID}
</div>
</>
)
}
}
Upvotes: 0
Views: 2033
Reputation: 1491
In your VisitorDetails.js
extract the id
from props as shown below. When you pass an id using react-router-dom
that id
will be added inside params
of the match
property from where you can access the id
value.
In your case as the path associated with the component is '/active/:id'
, you can access the value using id
prop as shown below
.........
.........
.........
componentDidMount() {
const { id } = this.props.match.params
axios.get(`http://localhost:8085/api/visitors/${id}`)
.then(res => {
this.setState({ visitors: res.data._embedded.visitorList });
})
.catch(error => {
console.log(error)
});
}
.........
.........
.........
Upvotes: 1