I have two buttons showing two different icons based on a state value. When the component first loads, I want one of the buttons to visible.
This is the code I have now:
<form
method="post"
action-xhr={`${hostName}/api/${itemId}/toggleFav`}
target="_top"
id="toggle-favorite-form"
dir="rtl"
encType="application/x-www-form-urlencoded"
>
<div className="add-to-fav-wrapper">
<div
className="ops-icon"
on={
'tap:AMP.setState({ favState: { newState: false }}),toggle-favorite-form.submit'
}
role="add-to-fav"
tabIndex="0"
data-amp-bind-hidden="favState.newState == false"
>
<Favorite />
</div>
<div
className="ops-icon"
on={
'tap:AMP.setState({ favState: { newState: true }}),toggle-favorite-form.submit'
}
role="remove-from-fav"
tabIndex="1"
data-amp-bind-hidden="favState.newState == true"
>
<NoneFavorite />
</div>
</div>
<input
hidden
name="newState"
data-amp-bind-value="favState.newState"
/>
<input
hidden
name="userId"
data-amp-bind-value="favState.userId"
/>
</form>
and this is the state:
<amp-state id="favState">
<script
type="application/json"
dangerouslySetInnerHTML={markup(
JSON.stringify({
userId: user?.id,
newState: !!isAddedTofav,
})
)}
/>
</amp-state>
The code works fine in the sense that it updates favorite correctly, but it just keeps showing the two buttons on page load.
I stumbled upon an official document from amp website on how to toggle favorites. I tried to adapt my solution by using the dynamic state, but that did not with amp hidden.
So eventually I decided to refactor the code like they did, and that worked.
Hopefully somebody can answer my question in the future.
Here's the link: