import React from 'react';
import axios from 'axios';
import {Table} from 'reactstrap';
class Newpage extends React.Component {
constructor(props){
super(props);
this.state = {
token: '',
items:[]
}
}
componentDidMount(){
axios.post(`https://gentle-escarpment-19443.herokuapp.com/v1/users/auth`,
{
email:"user1@email.com",
password: '!password!'
},
{headers: {
'Content-Type': 'application/json'
}})
.then(res => {
this.setState({
token: res.data.access_token
})
});
axios.get("https://gentle-escarpment-19443.herokuapp.com/v1/articles", {
headers: {
'Authorization': 'Bearer ' + this.state.token
}
})
.then((response)=>{
this.setState({
items: response.data
})
});
}
render() {
console.log(this.state.token)
let items = this.state.items.map((item) => {
return(
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.price}</td>
</tr>
);
});
return (
<div>
{this.state.token}
<Table>
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{items}
</tbody>
</Table>
</div>
);
}
}
export default Newpage;
Asked
Active
Viewed 698 times
2
Danil Valov
- 305
Name
- 31
1 Answers
1
У вас запрос авторизации асинхронный, ему нужно время, чтобы выполниться. Плюс время на добавление в state через setState. А запрос статей выполняется ещё до получения токена, поэтому и не проходит.
Вот это будет работать:
import React, {Component} from 'react';
import axios from 'axios';
import {Table} from 'reactstrap';
class Newpage extends Component {
constructor(props){
super(props);
this.state = {
token: '',
items: []
};
}
async componentDidMount(){
const authResponse = await axios.post(
'https://gentle-escarpment-19443.herokuapp.com/v1/users/auth',
{
email: 'user1@email.com',
password: '!password!'
},
{
headers: {
'Content-Type': 'application/json'
}
}
);
const token = authResponse.data.access_token
const articlesResponse = await axios.get(
'https://gentle-escarpment-19443.herokuapp.com/v1/articles',
{
headers: {
'Authorization': 'Bearer ' + token
}
}
);
const items = articlesResponse.data;
this.setState({
items,
token
});
}
render() {
const {token, items} = this.state;
return (
<div>
{token}
<Table>
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{
items.map(item => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.price}</td>
</tr>
))
}
</tbody>
</Table>
</div>
);
}
}
export default Newpage;
Danil Valov
- 305
localstorage.Потом проверяйте при каждом входе. – Randall Jun 20 '19 at 13:36