6. Actions

This "Learning Frontity" guide is intended to be read in order so please start from the first section if you haven't done so already.

Actions are a set of functions that your package need to work or exposes for other packages. They can modify the state and don't return anything.

Let's see one simple example:

actions: {
theme: {
openMenu: ({ state }) => {
state.theme.isMenuOpen = true;
},
closeMenu: ({ state }) => {
state.theme.isMenuOpen = false;
}
}
}

Actions are similar to derived state. They receive ({ state }) in their argument but that gets stripped out when you consume them:

actions.theme.openMenu();

And similar to derived state functions, they can also receive arguments if they are declared using a second function:

actions: {
theme: {
setMenu: ({ state }) => value => {
if (value === "open")
state.theme.isMenuOpen = true;
else if (value === "closed")
state.theme.isMenuOpen = false;
},
}
}

And they are consumed like this:

actions.theme.setMenu("open");

Actions can be used either by their own packages or by other packages.

For example, tiny-router (and all packages that want to implement the router API) exposes the action actions.router.set(). This action modifies state.router.link and makes sure that the URL of your browser is in sync. Additionally, tiny-router also runs this actions if users click on the back and forward buttons of their browsers.

By the way, you can access the actions in the client console using:

> frontity.actions

Actions triggered by Frontity

There are a set of special actions that Frontity runs at appropriate moments:

  • init โ€“ client and server โ€“ async Packages can use this action to initialize their internal libraries. Packages should not use actions or libraries from other packages as they could be not properly initialized.

  • beforeSSR: โ€“ server only โ€“ async The main purpose of this action is to prepare the state for the React render made in the server. Packages can populate it with content fetched from external APIs, like the WP REST API. They can also interact with other packages if necessary.

  • afterSSR: โ€“ server only This action runs when the HTML has been sent to the client. Packages should not rely in this action except for logging purposes because serverless providers sometimes kill the server after the HTML has been sent.

  • beforeCSR: โ€“ client only โ€“ async This action is run before React is hydrated. It's not widely used because here the state that React needs for the hydration is already received from the server.

  • afterCSR: โ€“ client only This action is run after React has been hydrated in the client and it has taken control of the page. This is where packages with client side logic can start doing their thing.