Reputation: 71
I need to access products that is inside a result from an API fetch. I tried multiple ways but is says or that map is undefined or something else.
Here's the imagem of the json response:
function getProducts(products) {
return request
.get(process.env.API_URL + 'url')
.send({
products: products,
})
.set('Content-Type', 'application/json')
.then((data) => console.log(data));}
Here is React component
constructor(props) {
super(props);
this.state = {
products: [],
};
}
componentDidMount() {
getProducts(this.state.products).end((err, data) => {
if (!err) {
this.setState({
products: data.body[0].products,
});
}
});
}
and my map function is inside render:
render() {
return (
<div>
{this.state.products.map((p, index) => (
Thanks for any advice!
Update
This is response for console.log(this.state.products)
Upvotes: 0
Views: 2529
Reputation: 5835
I had the same error message, what I'd done wrong is destructured an import that didn't need destructuring.
import { fetch } from "isomorphic-unfetch";
Should have been
import fetch from "isomorphic-unfetch";
Not sure if this solves your issue, but thought it was worth putting it down incase it helps someone else.
Upvotes: 1
Reputation: 71
The answer for that error was to change a bit getProducts function, remove all .then:
function getProducts(products) {
return request
.get(process.env.API_URL + 'url')
.send({
products: products,
})
.set('Content-Type', 'application/json')
});
}
Upvotes: 0
Reputation: 538
data
is not returned from your getProducts function. You are just console logging it. Return data
in your .then
callback function.
function getProducts(products) {
return request
.get(process.env.API_URL + 'url')
.send({
products: products,
})
.set('Content-Type', 'application/json')
.then((data) => {
console.log(data);
return data;
});
}
and then modify componentDidMount
function to
componentDidMount() {
getProducts(this.state.products).end((err, data) => {
if (!err) {
this.setState({
products: data.body.products,
});
}
});
}
Upvotes: 0