0

I am trying to display an array of news articles on the page and getting an error:

Unhandled Rejection (TypeError): this.state.newsPost.map is not a function

and this is my code that i am running:

import React, { Component } from 'react'
import { Container, Row, Col } from 'bootstrap-4-react';
import News from '../Articles/News';
import Post from '../Posts/Post/Post';
import axios from 'axios';
const REACT_APP_NEWS_ARTICLE_API = process.env.REACT_APP_NEWS_ARTICLE_API


export default class Body extends Component {
  constructor(props){
    super(props)

    this.state = {
      posts: [{}],
      newsPost: [{}]

    }
  }
   
  componentDidMount = (props) => {
    axios.all([axios.get(`${process.env.REACT_APP_SERVER_URL}/posts`), 
    axios.get(`https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${REACT_APP_NEWS_ARTICLE_API}`)])
      .then(axios.spread((...responses) => {
        const responseOne = responses[0]
        const responseTwo = responses[1]

        this.setState({
          posts: responseOne.data,
          newsPost: responseTwo.data
        })
      }
      
      ))

  };

  render() {
    console.log(this.state.newsPost) //returns an array of articles

    return (
      <Container id="bodycontainer" className="container">
        <Row className="technews">
        // This is the loop that's returning the error
        {this.state.newsPost.map((item) => {
          <div key={item.id} className="technewsitem">
            {item}
          </div>
        })}
        </Row>
      </Container>
    )
  }
}

How can I run the code in order to display the array on the page, any pointers is greatly appreciated.

  • Do you mean to use `forEach` instead of `map`? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – JoshG Mar 29 '21 at 09:20
  • Try replacing `map` with `foreach`. `map` returns an array. – Manas Khandelwal Mar 29 '21 at 09:20
  • 1
    Please give us a short example of the returned data. It is likely not an array but could likely be made to act like one - for example using Object.entries() – mplungjan Mar 29 '21 at 09:22
  • 1
    Also note that your `map` callback doesn't return anything, see [this question's answers](https://stackoverflow.com/questions/45754957/why-doesnt-my-arrow-function-return-a-value) for why. (This isn't the problem, the problem is that `responseTwo.data` isn't an array when you do `this.setState({ posts: responseOne.data, newsPost: responseTwo.data})`. But it'll be the *next* problem after you fix that.) – T.J. Crowder Mar 29 '21 at 09:26

1 Answers1

0
  1. Check if the value you are assigning to newsPost inside componentDidMount() is an Array
  2. Check data is an Array then use array methods

1

newPost && Array.isArray(newPost) ? newPost.map((value,index)=>{
//code 
}):<></>

2

    newPost.length>0 ? newPost.map((value,index)=>{
//code 
}):<></>
Sukesh
  • 167
  • 3
  • 14