3

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?

3 Answers 3

2
let data = this.state.data; //data from fetch request

data.forEach(item => array.push({ 
   text: `${item.content_title | ${item.content_subtitle}` 
}))
Sign up to request clarification or add additional context in comments.

Comments

2
let data = this.state.data; //data from fetch request
let arr = []
data.forEach(
 (item) => arr.push(item)
);

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.