1

I'm trying to create a load more function using a filtered set of entries, then passing those entries into the Load More component using Sprig.

I get the error "Impossible to invoke a method ("offset") on an array."

This is the code

Template

    {# If the user has selected "Auto" it'll auto populate below from section selected. #}
    {% if block.blockItemsManual|length %}
        {% set entries = block.blockItemsManual.entries.all() %}
    {% else %}
        {% set entries = craft.entries.section(block.blockItemsAuto).all() %}
    {% endif %}
    {# Show a Load More button that loads in more data via Sprig #}
    {{ sprig('_components/loadMore_grid', {'limit': 3, 'selectedEntries': entries }) }}
    {{ sprig.script }}

Component

{# Sets a default value if not defined by the `s-val:*` attribute on the button #}
{% set offset = offset ?? 0 %}

{% set entryQuery = selectedEntries.offset(offset).limit(limit) %}
{% set entries = entryQuery.all() %}


{% for entry in entries %}
......

1 Answer 1

2

Since you call .all() on the element queries, entries represents an array and therefore you cannot call .offset() on it. Leaving out .all() would allow you to call other functions on the query, for example:

{% set entryQuery = craft.entries.section(block.blockItemsAuto) %}

{% set entries = entryQuery.offset(offset).limit(limit).all() %}

However, when using Sprig you should never pass objects (or arrays of objects) into a component, see https://putyourlightson.com/plugins/sprig#component-variables :

Only primitive data types can be used as values: strings, numbers, booleans and arrays. Objects, models and elements cannot be used. If you want to pass an element (or set of elements) into a Sprig component then you should pass in an ID (or array of IDs) instead and then fetch the element from within the component.

So in this case I think you'd be better off either moving all of the logic into the component, or just passing an array of entry IDs into it.

1
  • I've used the array of entry IDs with success in a few instances. Can confirm it works great.
    – cherrykoda
    Commented Mar 7, 2023 at 4:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.