Reputation: 15
I'm pretty new to React and I've been struggling with fetching the data for quite a few days for my first React project.
I basically have a list of cards, split in two components: CardsList and Card. What I'm trying to do is to get the data for each card. My problem is, that I barely understood how fetching works for a single endpoint, and trying to fetch data from multiple endpoints at the same time seems to beat me.
I tried following an example from a blog explaining fetch, and came up with this:
export default class CardsList extends React.Component {
constructor(props) {
super(props);
this.state = {
details: [],
attachments: []
};
}
componentDidMount() {
//API and DEFAULT_QUERY have been set here, don't mind the ellipses
var API = '...';
var DEFAULT_QUERY = this.props.data;
var apiRequest1 = fetch(API + DEFAULT_QUERY, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
credentials: 'include',
}).then(response => response.json());
var apiRequest2 = fetch(API + DEFAULT_QUERY + '_attachment', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
credentials: 'include',
}).then(response => response.json());
var combinedData = {"apiRequest1":{},"apiRequest2":{}};
Promise.all([apiRequest1, apiRequest2]).then( values => {
combinedData["apiRequest1"] = values[0];
combinedData["apiRequest2"] = values[1];
return combinedData;
});
}
render() {
const { combinedData } = this.state;
let list = [];
for(var item of combinedData["apiRequest2"]) {
list.push(
<Card data={item} key={list.length}/>
);
}
return (
<div className="container">
<div className="row">
{list}
</div>
</div>
);
}}
As a first attempt I tried to feed the card component only the data from the second fetch. The console shows: "Uncaught TypeError: Cannot read property 'apiRequest2' of undefined".
I'm trying to learn a little bit from everywhere but I'm probably making things more confusing. What am I doing wrong and how should I go about this? Apologizes if I might seem confusing too.
EDIT: On the first fetch I'm trying to get the title, author and date of the card and on the second fetch I'm trying to get the preview image of the card.
The first fetch is something like this: data:[{title: "test", body: "test", author: "1", id: "1",...},…
and the second fetch: data:[{image_url: "abc.png", id: "1",...},...
Upvotes: 1
Views: 1630
Reputation: 614
The problem is in this line
const { combinedData } = this.state;
It equals to this
var combinedData = this.state.combinedData;
and I'm sure that this.state.combinedData is undefined; so this exception is thrown
Uncaught TypeError: Cannot read property 'apiRequest2' of undefined"
You'll need to add the default value for this.state.combinedData at the constructor so that the first render won't fail. After that you'll need to call
this.setState({
combinedData: ... // your data
})
at somepoint when your fetch request resolves.
Upvotes: 1