Skip to content

Commit

Permalink
doc: add upgrade information for Pinia migration
Browse files Browse the repository at this point in the history
  • Loading branch information
tajespasarela committed Jan 28, 2025
1 parent 29be204 commit a9de0c5
Showing 1 changed file with 52 additions and 125 deletions.
177 changes: 52 additions & 125 deletions guides/plugins/plugins/administration/system-updates/pinia.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,13 @@ With the release of Shopware 6.7, we will replace Vuex with [Pinia](https://pini

## Why Pinia?

Migrating to Pinia simplifies state management with an intuitive API,
no need for mutations, better TypeScript support, and seamless integration with Vue 3 Composition API.
It’s lightweight, modular, and offers modern features like devtools support, making it a more efficient alternative to Vuex.
Migrating to Pinia simplifies state management with an intuitive API, no need for mutations, better TypeScript support, and seamless integration with Vue 3 Composition API. It’s lightweight, modular, and offers modern features like devtools support, making it a more efficient alternative to Vuex.

## Migration Guide

To migrate a Vuex store to Pinia, you need to make some changes to the store definition and how you access it in components.

- First register it with `Shopware.Store.register` and define the store with `state`, `getters`, and `actions` properties:
- First, register it with `Shopware.Store.register` and define the store with `state`, `getters`, and `actions` properties:

Check warning on line 21 in guides/plugins/plugins/administration/system-updates/pinia.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] guides/plugins/plugins/administration/system-updates/pinia.md#L21

Add a space between sentences. (SENTENCE_WHITESPACE) Suggestions: ` Store` Rule: https://community.languagetool.org/rule/show/SENTENCE_WHITESPACE?lang=en-US Category: TYPOGRAPHY
Raw output
guides/plugins/plugins/administration/system-updates/pinia.md:21:34: Add a space between sentences. (SENTENCE_WHITESPACE)
 Suggestions: ` Store`
 Rule: https://community.languagetool.org/rule/show/SENTENCE_WHITESPACE?lang=en-US
 Category: TYPOGRAPHY

**Before (Vuex):**

Expand Down Expand Up @@ -87,15 +85,15 @@ Shopware.Store.unregister('<storeName>');

- To register a store from a component or index file, simply import the store file.

**Before (Vuex)**
**Before (Vuex):**

```javascript
import productsStore from './state/products.state';

Shopware.State.registerModule('product', productsStore);

Check warning on line 93 in guides/plugins/plugins/administration/system-updates/pinia.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] guides/plugins/plugins/administration/system-updates/pinia.md#L93

Add a space between sentences. (SENTENCE_WHITESPACE) Suggestions: ` State` Rule: https://community.languagetool.org/rule/show/SENTENCE_WHITESPACE?lang=en-US Category: TYPOGRAPHY
Raw output
guides/plugins/plugins/administration/system-updates/pinia.md:93:7: Add a space between sentences. (SENTENCE_WHITESPACE)
 Suggestions: ` State`
 Rule: https://community.languagetool.org/rule/show/SENTENCE_WHITESPACE?lang=en-US
 Category: TYPOGRAPHY
```

**After (Pinia)**
**After (Pinia):**

```javascript
import './state/products.state';
Expand All @@ -104,50 +102,55 @@ import './state/products.state';
### Key Changes

- **State:**

- In Pinia, `state` must be a function returning the initial state instead of a static object.

- Example:

```javascript
state: () => ({
productName: '',
})
```

- **Mutations:**

- Vuex `mutations` are no longer needed in Pinia, since you can modify state directly in actions or compute it dynamically.
- If a mutation only sets the state to a passed value, remove it and update the state directly in your action.
- If a mutation has extra business logic, convert it into an action.

- **Actions:**
- In Pinia, actions don't receive `state` as an argument. Instead, state is accessed directly using `this.anyStateField`.

**Example:**
-
```javascript
actions: {
updateProductName(newName) {
this.productName = newName; // Directly update state
},

- Example:

```javascript
actions: {
updateProductName(newName) {
this.productName = newName; // Directly update state
},
```
},
```

- **Getters:**

- There cannot be getters with the same name as a property in the state, as both are exposed at the same level in the store.
- Getters should be used to compute and return information based on state, without modifying it.
- It is not necessary to create a getter to return a state property. You can access it directly from the store instance.
- Avoid side effects in getters to prevent unexpected bugs. Getters should only compute and return information based on state, without modifying it.

- **TypeScript:**

- We recommend migrating JavaScript stores to TypeScript for stricter typing, better autocompletion, and fewer errors during development.
- To use the correct types when calling `Shopware.Store.get`, you can infer the store's type:
- Example:

```typescript
const store = Shopware.Store.register({

Check warning on line 141 in guides/plugins/plugins/administration/system-updates/pinia.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] guides/plugins/plugins/administration/system-updates/pinia.md#L141

Add a space between sentences. (SENTENCE_WHITESPACE) Suggestions: ` Store` Rule: https://community.languagetool.org/rule/show/SENTENCE_WHITESPACE?lang=en-US Category: TYPOGRAPHY
Raw output
guides/plugins/plugins/administration/system-updates/pinia.md:141:25: Add a space between sentences. (SENTENCE_WHITESPACE)
 Suggestions: ` Store`
 Rule: https://community.languagetool.org/rule/show/SENTENCE_WHITESPACE?lang=en-US
 Category: TYPOGRAPHY
id: 'myStore',

Check warning on line 142 in guides/plugins/plugins/administration/system-updates/pinia.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] guides/plugins/plugins/administration/system-updates/pinia.md#L142

This abbreviation for “identification” is spelled all-uppercase. (ID_CASING[2]) Suggestions: `ID` Rule: https://community.languagetool.org/rule/show/ID_CASING?lang=en-US&subId=2 Category: CASING
Raw output
guides/plugins/plugins/administration/system-updates/pinia.md:142:4: This abbreviation for “identification” is spelled all-uppercase. (ID_CASING[2])
 Suggestions: `ID`
 Rule: https://community.languagetool.org/rule/show/ID_CASING?lang=en-US&subId=2
 Category: CASING
...
});
export type StoreType = ReturnType<typeof store>;
```

- Then, you can use this type to extend `PiniaRootState`:
Then, you can use this type to extend `PiniaRootState`:

```typescript
import type { StoreType } from './store/myStore';
declare global {
interface PiniaRootState {
myStore: StoreType;
Expand Down Expand Up @@ -177,93 +180,46 @@ const store = Shopware.Store.register('<storeName>', function() {
});
```

### Accessing the Store

To access the store in Vuex, you would typically do:

```javascript
Shopware.State.get('<storeName>');
```

When migrating to Pinia, it changes to:

```javascript
Shopware.Store.get('<storeName>');
```

### Accessing State, Getters, Mutations, and Actions

Below is a practical example of how store access and usage changes from Vuex to Pinia:

**Before (Vuex):**

```javascript
// Get the store
const store = Shopware.State.get('product');
// Access the state
const productCount = Shopware.State.get('product').products.length;
// Use getters
Shopware.State.getters['product/productCount'];
// Execute mutations
store.commit('product/setProducts', [{ id: 1, name: 'Test' }]);
// Execute actions
store.dispatch('product/fetchProducts');
```
You can also use a composable function defined outside the store. This allows you to encapsulate and reuse logic across different stores or components, promoting better code organization and modularity:

```typescript
// composables/myComposable.ts
export function useMyComposable() {
const count = ref(0);

**After (Pinia):**
const doubled = computed(() => count.value * 2);

Check warning on line 190 in guides/plugins/plugins/administration/system-updates/pinia.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] guides/plugins/plugins/administration/system-updates/pinia.md#L190

If a new sentence starts here, add a space and start with an uppercase letter. (LC_AFTER_PERIOD[1]) Suggestions: ` Value`, ` value` Rule: https://community.languagetool.org/rule/show/LC_AFTER_PERIOD?lang=en-US&subId=1 Category: CASING
Raw output
guides/plugins/plugins/administration/system-updates/pinia.md:190:37: If a new sentence starts here, add a space and start with an uppercase letter. (LC_AFTER_PERIOD[1])
 Suggestions: ` Value`, ` value`
 Rule: https://community.languagetool.org/rule/show/LC_AFTER_PERIOD?lang=en-US&subId=1
 Category: CASING

```javascript
// Get the store
const store = Shopware.Store.get('product');
function increment() {
count.value++;

Check warning on line 193 in guides/plugins/plugins/administration/system-updates/pinia.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] guides/plugins/plugins/administration/system-updates/pinia.md#L193

If a new sentence starts here, add a space and start with an uppercase letter. (LC_AFTER_PERIOD[1]) Suggestions: ` Value`, ` value` Rule: https://community.languagetool.org/rule/show/LC_AFTER_PERIOD?lang=en-US&subId=1 Category: CASING
Raw output
guides/plugins/plugins/administration/system-updates/pinia.md:193:8: If a new sentence starts here, add a space and start with an uppercase letter. (LC_AFTER_PERIOD[1])
 Suggestions: ` Value`, ` value`
 Rule: https://community.languagetool.org/rule/show/LC_AFTER_PERIOD?lang=en-US&subId=1
 Category: CASING
}

// Access the state directly
const productCount = Shopware.Store.get('product').products.length;
function decrement() {
count.value--;

Check warning on line 197 in guides/plugins/plugins/administration/system-updates/pinia.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] guides/plugins/plugins/administration/system-updates/pinia.md#L197

If a new sentence starts here, add a space and start with an uppercase letter. (LC_AFTER_PERIOD[1]) Suggestions: ` Value`, ` value` Rule: https://community.languagetool.org/rule/show/LC_AFTER_PERIOD?lang=en-US&subId=1 Category: CASING
Raw output
guides/plugins/plugins/administration/system-updates/pinia.md:197:8: If a new sentence starts here, add a space and start with an uppercase letter. (LC_AFTER_PERIOD[1])
 Suggestions: ` Value`, ` value`
 Rule: https://community.languagetool.org/rule/show/LC_AFTER_PERIOD?lang=en-US&subId=1
 Category: CASING
}

// Use getters (no 'get' prefix)
const totalProducts = Shopware.Store.get('product').productCount;
return { count, doubled, increment, decrement };
}

// Mutate the state directly or through an action
Shopware.Store.get('product').products = [{ id: 1, name: 'Test' }];
// store/myStore.ts
import { useMyComposable } from '../composables/myComposable';

// Execute actions (called like methods)
Shopware.Store.get('product').fetchProducts();
const store = Shopware.Store.register('myStore', useMyComposable);

Check warning on line 206 in guides/plugins/plugins/administration/system-updates/pinia.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] guides/plugins/plugins/administration/system-updates/pinia.md#L206

Add a space between sentences. (SENTENCE_WHITESPACE) Suggestions: ` Store` Rule: https://community.languagetool.org/rule/show/SENTENCE_WHITESPACE?lang=en-US Category: TYPOGRAPHY
Raw output
guides/plugins/plugins/administration/system-updates/pinia.md:206:21: Add a space between sentences. (SENTENCE_WHITESPACE)
 Suggestions: ` Store`
 Rule: https://community.languagetool.org/rule/show/SENTENCE_WHITESPACE?lang=en-US
 Category: TYPOGRAPHY
```

In Pinia, you no longer need `commit` for mutations or `dispatch` for actions.
Instead, you can work with the state and call actions directly.

### MapState
### Accessing the Store

**Before (Vuex)**
To access the store in Vuex, you would typically do:

```javascript
const { mapState } = Shopware.Component.getComponentHelper();
export default {
computed: {
...mapState('product', ['products', 'productsCount']),
},
};
Shopware.State.get('<storeName>');

Check warning on line 214 in guides/plugins/plugins/administration/system-updates/pinia.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] guides/plugins/plugins/administration/system-updates/pinia.md#L214

Add a space between sentences. (SENTENCE_WHITESPACE) Suggestions: ` State` Rule: https://community.languagetool.org/rule/show/SENTENCE_WHITESPACE?lang=en-US Category: TYPOGRAPHY
Raw output
guides/plugins/plugins/administration/system-updates/pinia.md:214:7: Add a space between sentences. (SENTENCE_WHITESPACE)
 Suggestions: ` State`
 Rule: https://community.languagetool.org/rule/show/SENTENCE_WHITESPACE?lang=en-US
 Category: TYPOGRAPHY
```

**After (Pinia)** (using the Composition API):
When migrating to Pinia, it changes to:

```javascript
const { mapState } = Shopware.Component.getComponentHelper();
export default {
computed: {
...mapState(() => Shopware.Store.get('product'), ['products', 'productsCount']),
},
};
Shopware.Store.get('<storeName>');

Check warning on line 220 in guides/plugins/plugins/administration/system-updates/pinia.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] guides/plugins/plugins/administration/system-updates/pinia.md#L220

Add a space between sentences. (SENTENCE_WHITESPACE) Suggestions: ` Store` Rule: https://community.languagetool.org/rule/show/SENTENCE_WHITESPACE?lang=en-US Category: TYPOGRAPHY
Raw output
guides/plugins/plugins/administration/system-updates/pinia.md:220:7: Add a space between sentences. (SENTENCE_WHITESPACE)
 Suggestions: ` Store`
 Rule: https://community.languagetool.org/rule/show/SENTENCE_WHITESPACE?lang=en-US
 Category: TYPOGRAPHY
```

Remember to pass a function returning the store to `mapState`. `Shopware.Store.get` returns the store instance directly, while `mapStore` expects the `useStore` function. Also note that [mapGetters is deprecated](https://pinia.vuejs.org/api/pinia/functions/mapGetters.html), so you should rely on `mapState`.

### Testing

To test your store, just import it so it's registered. You can use `$reset()` to reset the store before each test:
Expand Down Expand Up @@ -310,32 +266,3 @@ describe('my component', () => {
});
});
```

Take into account that Pinia actions do not return a Promise. So to check DOM changes it might be necessary to await `nextTick()`;

```javascript
describe('MyComponent.vue', () => {
let wrapper;
const store = Shopware.Store.get('myStore');
beforeEach(async () => {
wrapper = mount(await wrapTestComponent('myComponent', { sync: true }), {
global: {
plugins: [createPinia],
},
});
});
it('increments the counter when the button is clicked', async () => {
store.increment();
// Wait for state updates and DOM reactivity
await nextTick();
// Assert the state and the DOM
expect(store.counter).toBe(1); // State change
expect(wrapper.find('p').text()).toBe('Counter: 1'); // DOM update
});
});
```

0 comments on commit a9de0c5

Please sign in to comment.