When developing a front end, there are times when you want to store a user-entered string or a selected value as state and send it to the server as a variable. In such cases, please follow the guide below for implementation.

Declaring State: defineState()

Use defineState() to declare your state. defineState() takes an object as an argument and sets it as the initial value.

import { defineState } from "@morph-data/components";

export const topPageState = defineState({
  dateRangeStart: new Date(),
  dateRangeEnd: new Date(),
  industry: "All",
});

Accessing the State Value: .value

You can access the value of the declared state by calling the .value property as shown below.

<>
  now: {topPageState.dateRangeStart.value.toLocaleString()}
  industry: {topPageState.industry.value}
<>

Tips
If it’s cumbersome to specify the variable name declared by topPageState. and defineState() every time as in this example, you can shorten it by destructuring the variables.

const { dateRangeStart, dateRangeEnd, industry } = defineState({
  dateRangeStart: new Date(),
  dateRangeEnd: new Date(),
  industry: 'All',
});

Updating the State: .update()

To update the state, use the update() method.

<Button onClick={() => topPageState.dateRangeStart.update(new Date())}>
  Reset date
</Button>

Using Input Components

In the Morph framework, there are components available for reflecting user input to the state declared with defineState(). For details, see Input Components. By using these input components, you can easily reflect user input in the state.

import { defineState } from '@morph-data/components';

export const topPageState = defineState({
  dateRangeStart: new Date(),
  dateRangeEnd: new Date(),
});

# My Data App page

Showing stock prices from {topPageState.dateRangeStart.value.toLocaleString()} to {topPageState.dateRangeEnd.value.toLocaleString()};

<DateRangePicker
  state={[
    topPageState.dateRangeStart,
    topPageState.dateRangeEnd
  ]}
/>

Passing Values to Data Components

Data components can accept a property called variables. By passing the values of the state declared with defineState() to this property, you can pass user-entered values to Python functions or SQL files.

By combining all the features we have seen so far, you can create a data app like the example below.

import { defineState } from '@morph-data/components';

export const topPageState = defineState({
  dateRangeStart: new Date(),
  dateRangeEnd: new Date(),
});

# My Data App page

Showing stock prices from {topPageState.dateRangeStart.value.toLocaleString()} to {topPageState.dateRangeEnd.value.toLocaleString()};

<DateRangePicker
  state={[
    topPageState.dateRangeStart,
    topPageState.dateRangeEnd
  ]}
/>

<DataTable
  alias="stocks"
  variables={{
    start_date: topPageState.dateRangeStart,
    end_date: topPageState.dateRangeEnd
  }}
/>