React patterns

Patterns used to manage map state and query/mutate data

useReducer

To organize the create, update, and delete actions that occur while using the project components map, useReducer is used to hold and modify state needed for the UI flows and also group state updates into actions organized into switch cases within a reducer function.

For example, to create a component, there are three pieces of state needed to move through the UI.

const [createState, createDispatch] = useReducer(createReducer, {
    isCreatingComponent: false, // track if user is creating
    showCreateDialog: false, // show initial dialog create form
    draftComponent: null, // hold data needed to create record
  });

The reducer function contains many cases that modify different combinations of this state.

For example, when someone starts creating a component and moves past the create form, we need to store what data we have so far. In the code, when the user clicks the Continue button that takes them to the map where they can begin selecting (or drawing) lines or points, we fire off the createDispatch function to update createState:

createDispatch({ type: "store_draft_component", payload: newComponent });

The type message is caught in a switch statement and the state updates like:

const createReducer = (state, action) => {
  switch (action.type) {
      case "store_draft_component":
            return {
                ...state, // the other current createState values
                draftComponent: action.payload, // data about the component
                isCreatingComponent: true, // tell the map code we are creating
            };
// ...the rest of the function

Last updated