In this episode, we dive into how to initialize stores in Alpine, which works in a very similar way to initializing regular Alpine components. If you're new to this, don't worry—we start off with a super simple example. We look at how you can use the x-init
directive or define an init
method inside your component or store to handle any setup or fetch actions when the component loads.
We then shift gears to a more practical, real-world example using a to-dos list store. You’ll see how we wire up an init
method that fetches a bunch of fake to-dos from an API (with JSONPlaceholder), logs the data, and then sets it on our store's state. You’ll learn how to output and loop through those to-dos in your markup for display, and how you can improve things by extracting a getter for easier access and better organization.
To wrap things up, we compare initializing the store from within (using the init
method) versus setting up state from the outside, and why keeping the initialization logic inside the store is usually cleaner and more maintainable. By the end, you’ll have a good grasp of initializing stores and why it’s best to handle setup inside the store itself.