A Beginner’s Guide to Global State Management in WordPress Gutenberg

When building complex WordPress block editor (Gutenberg) applications, managing state efficiently becomes crucial. This is where @wordpress/data comes into play. It allows you to manage and share global state across different blocks and components in your WordPress application.

If you’re new to managing global state or using @wordpress/data, don’t worry! This blog post will walk you through the basics of reducers, actions, and selectors, explaining how to use them to manage state in WordPress.

@wordpress/data provides a way to store, update, and access data globally, allowing different components or blocks to share and interact with the same data.



Key Concepts in @wordpress/data

To understand how to use @wordpress/data, we need to understand three main concepts: reducers, actions, and selectors. These form the core of how state is managed and updated.



Actions:

An action is like an instruction or command that tells the reducer what to do. It’s simply an object that has two parts:

  1. A type that indicates what kind of change is happening (e.g., add, remove, update).
  2. A payload that contains the data needed for that change (e.g., which item to add).

Here’s an example of how actions might look in our cart example:

const actions = {
    addToCart(item) {
        return {
            type: 'ADD_TO_CART', // Action type
            item // Payload: the item to add to the cart
        };
    },
    removeFromCart(itemId) {
        return {
            type: 'REMOVE_FROM_CART', // Action type
            itemId // Payload: the ID of the item to remove
        };
    }
};
Enter fullscreen mode

Exit fullscreen mode

In short: Actions tell the reducer what needs to change in the state.



Reducers:

A reducer is like a manager of your state. Whenever something changes in your application (e.g., a user adds a block or disables a feature), the reducer listens for that change and updates the state accordingly.

What does a reducer do? It takes the current state and an action, then returns a new state based on the action.
Here’s an example of a simple reducer that manages a shopping cart:

const reducer = (state = { cart: [] }, action) => {
    switch (action.type) {
        case 'ADD_TO_CART':
            return {
                ...state, // Keep the existing state
                cart: [...state.cart, action.item] // Add the new item to the cart
            };
        case 'REMOVE_FROM_CART':
            return {
                ...state,
                cart: state.cart.filter((item) => item.id !== action.itemId) // Remove the item from the cart
            };
        default:
            return state; // Return the unchanged state for unknown actions
    }
};
Enter fullscreen mode

Exit fullscreen mode

In short: The reducer defines how the state changes when specific actions are dispatched.



Selectors:

A selector is a function that retrieves or selects specific data from the state. When your components need to access data (like displaying the items in the cart), they use a selector to fetch that data from the store.

For example, a selector to get all the cart items might look like this:

const selectors = {
    getCartItems(state) {
        return state.cart; // Return the cart items from the state
    }
};
Enter fullscreen mode

Exit fullscreen mode

In a component, you would use this selector to access the cart data like this:

const cartItems = useSelect((select) => select('my-store').getCartItems());
Enter fullscreen mode

Exit fullscreen mode

In short: A selector is a helper function that lets you access specific data from the state.



Step by Step Guide to Implement Global State in Gutenberg with @wordpress/data

Now that we’ve covered the basics, let’s walk through how you can implement these concepts in a Gutenberg block or component. We’ll set up a simple store with @wordpress/data, manage some state, and use actions and selectors to interact with that state.

Step 1: Define Your Initial State
First, we need to define the initial state of our store. This is the default data that our application starts with:

const DEFAULT_STATE = {
    cart: []
};
Enter fullscreen mode

Exit fullscreen mode

Step 2: Create Actions
Next, we define the actions that we will use to update the state. In our case, we’ll define two actions: one to add an item to the cart and another to remove an item.

const actions = {
    addToCart(item) {
        return {
            type: 'ADD_TO_CART',
            item
        };
    },
    removeFromCart(itemId) {
        return {
            type: 'REMOVE_FROM_CART',
            itemId
        };
    }
};
Enter fullscreen mode

Exit fullscreen mode

Step 3: Create the Reducer
The reducer listens for dispatched actions and updates the state accordingly. Here’s our reducer, which updates the cart when actions are dispatched:

const reducer = (state = DEFAULT_STATE, action) => {
    switch (action.type) {
        case 'ADD_TO_CART':
            return {
                ...state,
                cart: [...state.cart, action.item]
            };
        case 'REMOVE_FROM_CART':
            return {
                ...state,
                cart: state.cart.filter((item) => item.id !== action.itemId)
            };
        default:
            return state;
    }
};
Enter fullscreen mode

Exit fullscreen mode

Step 4: Create Selectors
Selectors help retrieve specific data from the state. For example, if we want to get all items in the cart, we would create a selector like this:

const selectors = {
    getCartItems(state) {
        return state.cart;
    }
};
Enter fullscreen mode

Exit fullscreen mode

Step 5: Create and Register the Store
Finally, we’ll create and register the store with the @wordpress/data package. This will make the store globally accessible across your WordPress site.

import { createReduxStore, register } from '@wordpress/data';

const store = createReduxStore('my-cart-store', {
    reducer,
    actions,
    selectors,
});

register(store);
Enter fullscreen mode

Exit fullscreen mode

Step 6: Using the Store in Components
Once the store is registered, you can use it in your Gutenberg blocks or components. For example, to add an item to the cart:

import { useDispatch } from '@wordpress/data';

const { addToCart } = useDispatch('my-cart-store');
addToCart({ id: 1, name: 'Sample Item' });
Enter fullscreen mode

Exit fullscreen mode

To fetch the items in the cart:

import { useSelect } from '@wordpress/data';

const cartItems = useSelect((select) => select('my-cart-store').getCartItems());
Enter fullscreen mode

Exit fullscreen mode



Conclusion

By understanding the roles of reducers, actions, and selectors, you can easily manage global state in your WordPress Gutenberg projects using @wordpress/data. This structured approach allows you to manage data more efficiently, making your blocks and components more powerful and interactive.

With @wordpress/data, you have a reliable and scalable solution for handling state across your entire WordPress application. Give it a try in your next Gutenberg project!

Nuxt.js Data Fetching Hook: Async Data.

In this blog, I am discussing the Nuxt.js asyncData hook. For server-side rendering in Nuxt.js need to use specific hooks. This allows your page to render with all of its required data presents.



Nuxt.js has two hooks for asynchronous data loading:

  1. The fetch hook
  2. The asyncData hook

Also, Nuxt.js supports traditional Vue patterns for loading data in your client-side app, such as fetching data in a component’s mounted() hook.



Some important features of asyncData hook in Nuxt.js:

  1. asyncData works on both server-side & client-side rendering.
  2. asyncData is called every time before loading a component.
  3. You can use only on next pages, not in vue components.
  4. anyncData is called from the server-side before the component is mounted. That’s why you don’t have access to ’this’ keyword inside asyncData().
  5. This method receives the context object as the first argument and you can use it to access core nuxt properties such as route, store, params, app, etc.
  6. The result from asyncData will be merged with data.

Here is the example of nuxt asyncData using @nuxt/axios library:

<template>
  <div>
    <h1>{{ post.title }}</h1>
    <p>{{ post.description }}</p>
  </div>
</template>

<script>
  export default {
    async asyncData({params, $axios }) {
      const post = await $http.$get(`https://api.nuxtjs.dev/posts/${params.id}`)
      return { post }
    }
  }
</script>
Enter fullscreen mode

Exit fullscreen mode

asyncData hook returned the promise and resolved during the route transition. This means that no “loading placeholder” is visible during client-side transitions but you can use the loading bar can be used to indicate a loading state to the user.



asyncData() on both client-side & server-side:

To test how asyncData() works on both client-side & server-side, please write the bellow code on your Nuxt.js page.

<script>
export default{
    asyncData(context){
        console.log(context);
}
}
</script>
Enter fullscreen mode

Exit fullscreen mode

Server Side Test
Now reload the page on the browser and look inside your terminal(also can check on browser console panel Nuxt SSR Response) on which your Nuxt.js application running. You can see the context object like the below screenshot. That means its works on the server-side.
Nuxt.js SSR

Client Side Test
You can also check client-side rendering when you come to this page from another Nuxt.js page (The link must be used NuxtLink for linking between pages). Now open your browser dev tools and check the console panel and you see the magic of asyncData().
Client Side Test Nuxt.js



How you can use Async data in components:

We already know that we can not use anyncData hook inside any component but we can use another way for component.
Make the API call in the asyncData method of the page component and pass the data as props to the sub components. Both Client & Server side rendering will work fine.

Referance: Nuxt.js Official Data Fetch Hook

How to Use Nuxt.js Loading Progress Bar

Are you using Nuxt.js on your current project as front-end framework? then you have a great news, Nuxt.js Out of the box gives you its own loading progress bar component that’s shown between routes. You can do anything with the Nuxt.js loading progress bar, customize it, disable it, or can create your own loading progress bar.



Active & Customize Progress Bar:

You can activate the progress bar on your Nuxt.js application by adding the loading property of the nuxt.config.js inside the export default { //code here } with the corresponding properties.

To set a green progress bar with a height of 5px, add the following code inside your project nuxt.config.js file.

export default {
  loading: {
    color: 'green',
    height: '5px',
    throttle: 0
  }
}
Enter fullscreen mode

Exit fullscreen mode

You can customize many things, you can change color(color name/color hex code), height, duration, direction for rtl sites, keep animating progress bar when loading takes longer than duration.

export default {
  loading: {
    color: 'green',
    height: '5px',
    duration: 1000,
    rtl: true,
    continuous: true
  }
}
Enter fullscreen mode

Exit fullscreen mode



Disable the Progress Bar:

You can disable the progress bar globally or locally. If you want to disable the progress bar globally then add loading: false in your nuxt.config.js file:

export default {
  loading: false
}
Enter fullscreen mode

Exit fullscreen mode

Your can also disable the progress bar for specific page. Add loading: false in the specific page.

<template>
  <h1>Contact Us Page</h1>
</template>

<script>
  export default {
    loading: false
  }
</script>
Enter fullscreen mode

Exit fullscreen mode



Custom Loading Progress Bar:

You can also create your own custom loading progress bar. Inside the component directory create your custom component in LoadingBar.vue:

<template>
  <div v-if="loading" class="loading-page">
    <p>Loading...</p>
  </div>
</template>

<script>
  export default {
    data: () => ({
      loading: false
    }),
    methods: {
      start() {
        this.loading = true
      },
      finish() {
        this.loading = false
      }
    }
  }
</script>

<style scoped>
  .loading-page {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.8);
    text-align: center;
    padding-top: 200px;
    font-size: 30px;
    font-family: sans-serif;
  }
</style>
Enter fullscreen mode

Exit fullscreen mode

Then go to nuxt.config.js file and add your custom loading component to the loading property.

export default {
  loading: '~/components/LoadingBar.vue'
}
Enter fullscreen mode

Exit fullscreen mode

It’s very simple, right? Now you can see your own custom loading bar between routes changing.



Useful Links:

Lets work together

Need a successful project?

I'm available for freelance work.

Hire/Contact Me Now