1

I Have a sprig component that has two variables, but the moment Sprig changes one of them, the other value resets. Please Help

products.twig

{% extends "_layout/base" %}

{% set wrapClass = 'category' %} 


{% block body %}

    <section class="spacer pt-6"></section>
    {% include "_shared/breadcrumbs" %}
    <section class="spacer pt-6"></section>
    {{sprig("_shared/sprig2", {count: 20 })}}

{% endblock %}

_sprig2.twig

{% set count = count ?? 12 %}
{% set offset = offset ?? 0 %}


<button sprig  s-val:count="{{ count + 3 }}">three more..
    {{count}}
</button>

    <button sprig s-val:offset="{{ offset + 3 }}">three more..
    {{offset}}
</button>


{{ sprig.script }}

In this example, If I click count, offset resets and if I do offset, the count resets, Please Help.

1 Answer 1

1

You can maintain state within your component either by using a hidden input field:

{{ hiddenInput('count', count) }}

Or by adding another s-val attribute to each button.

<button sprig s-val:count="{{ count + 3 }}" s-val:offset="{{ offset }}">
    ...
</button>

<button sprig s-val:offset="{{ offset + 3 }}" s-val:count="{{ count }}">
    ...
</button>

Since s-val is inherited, you can add it to a parent element for convenience.

<div s-val:count="{{ count }}" s-val:offset="{{ offset }}">
    <button>...</button>
    <button>...</button>
</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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