#Create Pinia Store with complex data types
1 messages · Page 1 of 1 (latest)
To implement complex data types like nested objects in your Pinia store for the address fields, you need to define interfaces or types for your address structure and then use those types in your store definition. Here's how you can modify your store:
First, define an interface for your address structure:
interface Address {
country: string;
city: string;
postalCode: string;
street: string;
houseNumber: string;
doorNumber: string;
}
Then update your store to use this interface:
export const useUserStore = defineStore('user', {
state: () => {
return {
billingAddress: {} as Address,
email: '' as string,
firstName: '' as string,
lastName: '' as string,
phoneNumber: '' as string,
preferredPaymentMethod: '' as string,
role: '' as string,
shippingAddress: {} as Address,
isAuthenticated: false as boolean,
registered: false as boolean,
};
},
actions: {
clearStore() {
this.billingAddress = {} as Address;
this.email = '';
this.firstName = '';
this.lastName = '';
this.phoneNumber = '';
this.preferredPaymentMethod = '';
this.role = 'User';
this.shippingAddress = {} as Address;
this.isAuthenticated = false;
},
},
persist: {},
});
This approach is similar to what's shown in the Stack Overflow examples where complex data structures are used in Pinia stores. For example, in this Stack Overflow post, you can see how to work with complex types in Pinia stores.
When you receive the API response, you can update your store like this:
// Example of updating the store with API response
const userStore = useUserStore();
userStore.billingAddress = apiResponse.billingAddress;
If you need to add specific actions to handle address updates, you can add them to your store:
actions: {
// ... existing actions
updateBillingAddress(address: Address) {
this.billingAddress = address;
},
updateShippingAddress(address: Address) {
this.shippingAddress = address;
}
}