Reputation: 445
I'm trying to add data to an array of objects that will look like this:
[
{text: 'title content | subtitle content'},
{text: 'more title content | and more subtitle content'},
{text: 'even more title content | and some more subtitle content'}
]
My data is coming from a fetch request, returning an array of objects. I'm trying to set the data that I receive from the fetch request to an array called 'array', like this:
let data = this.state.data; //data from fetch request
array.push(data.map(item, i) => {
{text: `{item.content_title | {item.content_subtitle}`}
});
I've placed the above codeblock in the componentDidMount()
lifecycle method. I'm getting a parsing error when running this code. How can I push the fetched data to the array?
Upvotes: 3
Views: 1854
Reputation: 620
Part of the issue could be your fetch has not yet returned, so this.state.data is null. If the format of the data you need is an array of objects, store that in state. In this example you get your fetch data (and don't forget .json() if returning JSON), process it, and store in state. Also, in your example, you forgot the $ for the text string.
fetch("some url")
.then(res => res.json()) // if JSON returned
.then(json => {
const data = json.map(item => {
return {text: `${item.content_title} | ${item.content_subtitle}`};
}
this.setState({ data });
}).catch(console.error);
Upvotes: 1
Reputation: 352
let data = this.state.data; //data from fetch request
data.forEach(item => array.push({
text: `${item.content_title | ${item.content_subtitle}`
}))
Upvotes: 2
Reputation: 246
let data = this.state.data; //data from fetch request
let arr = []
data.forEach(
(item) => arr.push(item)
);
Upvotes: 2