Karthi
Karthi

Reputation: 3489

array.forEach is not a function

I'm showing array of objects that is received from api call.I'm using react hooks.when I tried to iterate through array of objects it return foreach is not a function. for this can I use await and async.

function searchArticle() {

    const [articleList, setArticleList] = useState([]); 
    const { articleApiStatus, articleCurrentPage, searcArticle } = state;
    useEffect(() => {
        setArticleList(state.articleList);
        articleListApiCall(articleCurrentPage);
    }, [])

    const articleListApiCall = (page = 1) => {
        const isNewPage = articleCurrentPage !== page;
        if (!articleApiStatus || isNewPage) {
            getArticleList(page, '')
        }
    }
    const getArticleList = async (page, searchkey) => {
         const requestBody = {
            page: page - 1, searchkey
        }
        await onArticleSearchPost(requestBody).then(articleresult => {
            setArticleList(articleresult);          
        }).catch(err => {
            console.log(err);
        })
    }   
    return (
        <React.Fragment>
            <div className="article-section">
              <div className="search-result">
                <Collapse  >
                {
                        articleList.forEach(element => {
                        <Panel header={element.article_title} key={element._id}>
                          <p>{element.article_body}</p>
                        </Panel>
                        })
                }
              </div>
              <div className="pagination-section">
                  <Pagination defaultCurrent={1} total={50} />
              </div>
            </div>                
        </React.Fragment>
    )
}
export default searchArticle;

Edit : I'm receiving following data from api call

[ 
   {       
      "_id":"5d9efbc3b29b2876700adf6f",
      "postedBy":"Admin",
      "datePosted":"1570700227888",      
      "__v":0
   }   
]

Upvotes: 1

Views: 3396

Answers (1)

Clarity
Clarity

Reputation: 10873

First of all, do not use forEach to render JSX, it won't work. Use map instead:

<Collapse>
  {articleList.map(element => { // use map
    return (
      <Panel header={element.article_title} key={element._id}>
        <p>{element.article_body}</p>
      </Panel>
    );
  })}
</Collapse>

Second, make sure that state.articleList, which you're setting to state in useEffect, is an actual array.

Upvotes: 7

Related Questions