Search code examples
reactjsnext.jswordpress-rest-apiheadless-cms

How to skip 'null' elements when mapping array in react


It seems like I'm getting the posts array fine like below

posts: [ ]
0: { }
1: { }
2: null
3: null
4: { }

Not sure why some of them are null? Im using nextjs and headless wordpress. Anyone know of a solution to skip over the nulls? or maybe Im not calling the right posts?

Thanks in advance!


Solution

  • you can't do it with map,

    it will be better if you just filter it out before mapping

    posts
    .filter(x => x !== null) // this step will remove nulls
    .map(x => {/* your logic */})