#set nanostore whenever page navigation occurs
4 messages · Page 1 of 1 (latest)
Hi @heady pecan. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, you can detect when page navigation occurs in Astro by using the astro:page-load event. This event fires at the end of page navigation, after the new page is visible to the user and blocking styles and scripts are loaded. You can listen to this event on the document. Here's an example of how you can use it:
<script>
document.addEventListener('astro:page-load', () => {
// Your code here. For example, you can set your nanostore value here.
});
</script>
To set a value in a nanostore, you can use the .set method. Here's an example of how you can set a value in a nanostore:
import { atom } from 'nanostores';
export const isCartOpen = atom(false);
// To set a value
isCartOpen.set(true);
So, you can combine these two to set a nanostore value whenever page navigation occurs:
import { atom } from 'nanostores';
export const isCartOpen = atom(false);
<script>
document.addEventListener('astro:page-load', () => {
isCartOpen.set(true);
});
</script>
Please note that this code should be placed in a client-side script, as Astro's lifecycle events are client-side only.
Sources:
- Astro: Page Load Event (https://docs.astro.build/en/guides/view-transitions/#astropage-load)
- Nano Stores (https://docs.astro.build/en/recipes/sharing-state-islands/#using-atoms)
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@heady pecan kapa.ai is still learning and improving, please let us know how it did by reacting below