reduce method

  1. @override
Future<CoreState?> reduce()

The reduce method is the action reducer. It may read the action state, the store state, and then return a new state (or null if no state change is necessary).

It may be synchronous (returning AppState or null) or async (returning Future<AppState> or Future<null>).

The StoreConnectors may rebuild only if the reduce method returns a state which is both not null and different from the previous one (comparing by identical, not equals).

Implementation

@override
Future<CoreState?> reduce() async {
  final String? uid = state.userState!.auth!.uid;

  // Send events only when the uid exists in the core state and when the user
  // is logged in
  if (uid != null && uid != UNKNOWN) {
    final Map<String, dynamic> _variables = processEventMutationVariables(
        eventName: eventName, uid: uid, payload: eventPayload);

    final Response response =
        await client.query(processEventMutation, _variables);

    client.close();

    if (response.statusCode == 408) return null;

    final Map<String, dynamic> logResponse = client.toMap(response);

    // check for errors here first
    final String? logError = client.parseError(logResponse);

    if (logError != null) return null;

    if (logResponse['data'] != null &&
        logResponse['data']['processEvent'] != true) {
      /// Encode the eventPayload to a string and save the event to state
      dispatch(SaveEventAction(
          eventName: eventName, eventPayload: json.encode(eventPayload)));

      Future<void>.delayed(
        Duration(seconds: retryPeriod),
        () async {
          final EventState? eventState = state.miscState!.eventState;

          final String eventName = eventState!.eventName!;
          final String eventPayload = eventState.eventPayload!;

          final Map<String, dynamic> _payload =
              json.decode(eventPayload) as Map<String, dynamic>;
          dispatch(
            SendEventAction(
              client: client,
              eventName: eventName,
              eventPayload: _payload,
            ),
          );
        },
      );
    } else {
      return state;
    }
  }
  return null;
}