skip to Main Content

I’m trying to make the following code work but I’m getting a syntax error after the displayPosts(posts); call: Unexpected token, expected "{"

{hasPostsResolved && posts?.length > 0 &&
    displayPosts(posts);
    <input type="button" className="wp-element-button" value="Load More" />
}

For completeness:

const { posts, hasPostsResolved } = useSelect(select => {
    const query = {
        order: 'desc',
        orderby: 'date',
        status: 'publish',
        categories: category ? category : [],
        per_page: number
    };
    return {
        posts: select('core').getEntityRecords('postType', 'post', query),
        hasPostsResolved: select('core').hasFinishedResolution('getEntityRecords', ['postType', 'post', query]),
    }
}, [category, number]);

const displayPosts = (posts) => {
    return (
        posts.map((post, index) => {
            return (
                <article id={`post-${post.id}`} key={index}>
                    <h2>
                        {
                            post.title.rendered ?
                            decodeEntities(post.title.rendered) :
                            __('(no title)')
                        }
                    </h2>
                    <div dangerouslySetInnerHTML={{ __html: post.content.rendered }} />
                </article>
            )
        })
    )
};

Can someone tell what’s wrong with my code? I can’t make it work for the life of me.

2

Answers


  1. Maybe you meant the following? I’m assuming that displayPosts is a function that returns JSX.

    {hasPostsResolved && posts?.length > 0 &&
        <>
            {displayPosts(posts)}
            <input type="button" class="wp-element-button" value="Load More" />
        </>
    }
    
    Login or Signup to reply.
  2. Guillaume Brunerie’s answer is 100% correct and is what I was going to answer however I did want to mention that there is no reason for displayPosts to not be a component. I would update the code like this:

    const DisplayPosts = ({posts}) => {
        return (
            // ...
        )
    };
    
    {hasPostsResolved && posts?.length > 0 &&
        <>
            <DisplayPosts posts={posts} />
            <input type="button" class="wp-element-button" value="Load More" />
        </>
    }
    

    I apologize for making essentially a duplicate answer but this was just a bit long for a comment.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search