Use state management

This topic introduces the basics of using Goldfish state management to develop mini programs.

Overview

Goldfish provides a comprehensive response-based state management solution for mini program development projects, with the following key features:

  • Composition API: Contains a set of APIs that allows us to author mini program modules (App, Page, and Component) using imported functions instead of declaring options.
  • Reactivity: Provides the reactivity ability like Vue. You can write less code to express more complex logic.

Create reactive data

You can use the useState function to create reactive data in the execution environment of Composition API:

copy
// File path: src/pages/index/index.ts
import { useSetup, useState, setupPage } from '@goldfishjs/core';

function useBiz() {
  // Reactive data
  const state = useState({
    name: 'Jack',
    // Computed property: The value of fullName will be automatically recalculated after this.name is changed, otherwise, the last calculation result is always returned.
    get fullName() {
      return `${this.name} Ma`;
    },
    // Set the value of fullName
    set fullName(val) {
      this.name = val.split('.').slice(0, -1).join('.');
    },
  });

  setTimeout(() => {
    // Change the value of state.name, and state.fullName will then be calculated automatically.
    state.name = 'God';
  }, 1000);

  return { state };
}

Page(setupPage(useBiz));

Read data in AXML:

copy
<!-- File path: src/pages/index/index.axml -->
<view>{{ state.name }} - {{ state.fullName }}</view>

You can also use these three decorators: state, computed, and observable to turn any class into a reactive one:

copy
// File path: src/store/FormData.ts
import { observable, state, computed } from '@goldfishjs/core';

/* FormData can be normally instantiated anywhere, 
 including Composition API execution environment. */
@observable
class FormData {
  @state
  public name: string = 'Jack Ma';

  @computed
  public get fullName() {
    return this.name;
  }
}

Consume reactive data

The following sections provide how the reactive data is consumed.

Consume data in AXML of mini program

In the AXML files of pages and components, you can read the final returned value in the execution environment of Composition API:

copy
// File path: src/pages/index/index.ts
import { setupPage, useState } from '@goldfishjs/core';

function useBiz() {
  const state = useState({
    name: 'Jack Ma',
  });

  // The final returned value in Composition API execution environment
  return {
    state,
  };
}

Page(setupPage(useBiz));

Read data in AXML:

copy
<!-- File path: src/pages/index/index.axml -->
<view>{{ state.name }}</view>

Listen for reactive data changes

In the execution environment of Composition API, you can listen for changes to the reactive data using the watch or autorun function:

copy
// File path: src/pages/index/index.ts
import { setupPage, useState, useWatch, useAutorun } from '@goldfishjs/core';

function useBiz() {
  const state = useState({
    name: 'Jack Ma',
  });

  // Listen for data changes with watch
  const watch = useWatch();
  watch(
    () => state.name,
    (newVal, oldVal) => {
      console.log(`state.name changed: ${oldVal} -> ${newVal}`);
    },
  );

  // Listen for data changes with autorun
  const autorun = useAutorun();
  autorun(() => {
    console.log(`state.name current value: ${state.name}`);
  });

  return {
    state,
  };
}

Page(setupPage(useBiz));

Understand local state and global state

The following sections introduce local state and global state.

Local state

Local state refers to the state generated by useState, which corresponds to the state data used in Page and Component. The state data is created or destroyed as the page instance or component instance is created or destroyed.

copy
// File path: src/pages/index/index.ts
import { setupPage, useState } from '@goldfishjs/core';

function useBiz() {
  // State data is created or destroyed as page instances are created or destroyed.
  const data = useState({
    name: 'Jack Ma',
  });

  return {
    data,
  };
}

Page(setupPage(useBiz));

Global state

Global state refers to the state data covering the entire lifecycle of App. You can access the global data with the useGlobalData function:

copy
// File path: src/pages/index/index.ts
import { useGlobalData, setupPage } from '@goldfishjs/core';

function useBiz() {
  // Get the global data object
  const globalData = useGlobalData();
  return {
    get name() {
      // Access the global data
      return globalData.get('name');
    },
    setName(val) {
      // Change the global data
      globalData.set('name', val);
    },
  };
}

Page(setupPage(useBiz));

Note: You can listen for the change of globalData.get('name') by the watch function only when the name data exist in globalData. Otherwise, the listening will be invalid.

More information

State management