Reputation: 21
Please help me,
I want get data from api with axios and result return listview, but i get an error, it doesn't seem to return array
import React, { lazy, Component } from "react";
state = { data: [] }
class ProductListView extends Component {
getProducts = () => {
this.setState({ data: [{'obj': 'value'}] });<br/>
console.log(this.state.data);
return this.state.data;
};
}
export default ProductListView;
result return console.log:
Array [ { obj: "value" } ]
function products.slice is ok
but when i get api
...
getProducts = () => {
let res = UserService.getAll().then(response => response.data);
this.setState({ data: res });
console.log(this.state.data);
return this.state.data;
};
...
result return console.log:
Promise { <state>: "pending" }
<state>: "fulfilled"
<value>: Array(18) [ {…}, {…}, {…}, … ]
TypeError: products.slice is not a function
Hope to get an answer , tks
Upvotes: 0
Views: 110
Reputation: 12777
You should use async/await
in this case:
getProducts = async () => {
let res = await UserService.getAll();
console.log(res.data);
this.setState({ data: res.data });
};
Upvotes: 1