0

I've searched other posts but couldn't quite find I was looking for. I am looping through data from a sanity api but I want to limit it to just the first 4 items returned. What would be the best way to achieve this? Here is the code in question

 {mappedPosts && mappedPosts && mappedPosts.map ( (post) => (
                    <Col className="mapped-posts" style={redLine} xs="12" lg="4">
                        <div style={imageContainerStyle} onClick={() => router.push(`/logos/${post.slug.current}`)} key={post.index} >
                                <img
                                    src={post.mainImage}
                                alt={post.title}
                                style={imgStyle}
                                layout="fill" />
                            <h3 style={titleStyle}>{post.title}</h3>
                            </div>
                    </Col>
                    )) }   

Can I do something in the loop like:

{mappedPosts && mappedPosts.length < 4 && mappedPosts.map ( (post) => (

Or is there a better way to control how much data is returned with the map function?

SJK
  • 91
  • 1
  • 10

1 Answers1

0

You can take only the first 4 item and loop immediatly after

mappedPost.splice(0, 4).map( (post)=> ....
Erikwski
  • 39
  • 6
  • `splice` **modifies** the original array, which you must not do with React state items (and doesn't make sense here anyway). The linked earlier question already shows a correct solution (`slice`, not `splice`). – T.J. Crowder Feb 17 '23 at 11:26
  • Thanks people of SO, yep, have used slice. I thought I saw a post on SO earlier where someone used ```length``` but can't find it now hence posting - what would be more proper to use ```slice``` or ```length``` ? – SJK Feb 17 '23 at 11:33
  • @SJK - `slice` (**not** `splice` as in this answer). Using `length` doesn't make sense, it doesn't give you an array to map like `slice` does. – T.J. Crowder Feb 17 '23 at 11:39