Preserve application state in ngrx with a dedicated theme

There is a feature switcher that changes the appearance of the application visually. It only returns boolean values.

I have a service with a button in the header that triggers the following function:

@Injectable({
  providedIn: 'root',
})
export class ThemeService {
  public _darkTheme$$: Observable<boolean> = this.store.select(selectChanges);

  constructor(private store: Store) {}

  setTheme(theme: boolean) {
    this.store.dispatch(changeTheme({ change: theme }));
  }
}

Next, let's look at the header code:

toggleTheme(theme: boolean): void {
    this.themeService.setTheme(theme);
  }

Here's how it looks in the HTML:

<mat-slide-toggle
     [checked]="themeService._darkTheme$$ | async"
     (change)="toggleTheme($event.checked)"
  ></mat-slide-toggle>

The data in the storage gets updated properly. However, when creating a module effect, I encounter multiple errors.

This is the effect for the storage:


@Injectable()
export class ThemeEffect {
  constructor(private actions$: Actions, private themeService: ThemeService) {}

  // @ts-ignore
  toggleTheme$ = createEffect(() => {
    return this.actions$.pipe(
      ofType(changeTheme),
      mergeMap((change: { change: boolean }) => {
        return this.themeService.setTheme(change.change);
      }),
    );
  });
}

Answer №1

In order for an effect to work effectively, it should always return an action that can be dispatched to the store. It seems like themeService.setTheme does not return an action, but rather needs to be invoked directly. As a result, you will need to define the effect as a non-dispatching effect.

@Injectable()
export class ThemeEffect {
  constructor(private actions$: Actions, private themeService: ThemeService) {}

  // @ts-ignore
  toggleTheme$ = createEffect(() => {
    return this.actions$.pipe(
      ofType(changeTheme),
      mergeMap((change: { change: boolean }) => {
        return this.themeService.setTheme(change.change);
      }),
      // map(
      //   (i) => this.themeService.setTheme(i.change),
      //   catchError((err) => throwError(err)),
      // ),
    );
  // 👇
  }, { dispatch: false});
}

On a side note: Remember to include any errors encountered when creating an issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

invoking a method of the grandparent from within the grandchild component

My components are nested three levels deep: <GrandParent /> <Parent /> <Child /> In the Child component, I have a button that, when double clicked, should call a function in the GrandParent component. <button @dblclick=&quo ...

What is the process for choosing a contact once it has been located? Ionic 2

I'm currently working on a feature that involves selecting an option from a list. After performing a search, I want to be able to select the desired option and have it displayed in the search bar like shown in this example. Here's my progress so ...

Ways to implement HemisphereLight with ShaderMaterial?

I am facing an issue where I am trying to light an object that has been created with ShaderMaterial using HemisphereLight, but the object does not appear to be affected by any of the lights. I have tested it with various other lights as well, and none seem ...

Instructions on creating a number increment animation resembling Twitter's post engagement counter

I've been attempting to replicate the animation seen on Twitter's post like counter (the flipping numbers effect that happens when you like a post). Despite my best efforts, I can't seem to make it work. Here is what I have tried: $(fun ...

The current PHP value updates every 10 seconds, but I would like it to load instantly when the page loads

Currently, I have a script in place that updates the placeholder field of an input textbox with the latest bitcoin price every 10 seconds: var auto_refresh = setInterval( function() {$.get('gox.php', function (data) { $("#inputid").attr( ...

What are the TypeScript types needed for a React component that accepts an array of objects as a prop?

I am currently working on a React component that includes a prop named propWhichIsArray. This prop is expected to be an array of objects. Each object in the array will contain properties such as id (an ID) and text (a string). How do I properly define this ...

How to send data from JavaScript to ASP.NET

$(document).ready(function () { $("#MainContent_ddlFieldName").on("change", function () { var id = $(this).val(); var name = $(this + "option:selected").text(); $('#<%= lblValue.ClientID %> ...

Including numerous pins on a map

I am currently working on a project that involves extracting data from PHP records to plot markers on a leaflet map using coordinates. Unfortunately, I encountered an error in the console: Error: Invalid LatLng object: (18.473396, undefined) Here is th ...

What is the method for adjusting the size of text while rendering on a canvas?

When it comes to scaling text with CSS transform scale, for instance: transform: scale(2, 4); fontSize: 20px // Is including fontSize necessary? I also have the task of displaying the same text on a canvas element. function draw() { const ctx = document ...

Unable to retrieve element by class from external HTML source: undefined

By utilizing an HTTP get request, I am pulling in HTML blocks from an external source and inserting them into my application using the innerHTML function. My aim is to locate a div class by its class name with getElementsByClassName. The response that I re ...

What advantages does utilizing NPM provide compared to directly incorporating the JavaScript library into an MVC project?

When working on an MVC project, I experimented with two different methods of including jQuery: I first downloaded the jQuery files and manually added them to the project, as shown here: https://i.sstatic.net/2TjqX.png I also tried using the bundle sett ...

``Why Ionic 3 Popover Sizes Should Adapt to Different Screen

Currently in my Ionic 3 project, I am utilizing a popover with a set height using the following code snippet: editOpty(rw){ let popover = this.editOptyPopup.create(EditOptyPopoverComponent, rw, { cssClass: 'edit-opty-popover'}); popover ...

What is the process of transforming this jQuery script into AngularJS code?

Currently I am facing a situation where I am utilizing Angular1.x for a project. On a specific subpage, there are small clickable images along with some additional content below these images. The requirement is that only the images should be visible init ...

Organizing a NodeJS module - properties and functions

I've been struggling to structure my NodeJS application with modules, and after hours of searching, I haven't found a definitive answer. Let's say I want to create a "user" module for creating new users in my code: var newUser = new User(); ...

What is the best way to construct a JSON object for React based on the data from a JSON API response?

My API will be sending back data in the following format: [ { "id":5, "name":"Example", }, { "id":634, "name":"Test", }, ... ] In my React application, I need to create a JSON object like this: const fields = ...

Error in AWS Lambda: JSON parsing error due to unexpected token 't' at position 6

I'm currently working on a basic lambda function that utilizes a post request to insert data into DynamoDB. However, every time I deploy the lambda function and test it using Postman, I keep encountering a 502 Bad Gateway error. To troubleshoot this ...

Sending messages to a different page: A step-by-step guide

I need to create buttons that, when clicked, will send a specific message or number to another page. For example, clicking button 1 should send "1" and clicking button 2 should send "2". I am looking for a way to achieve this functionality using either j ...

Load ajax content dynamically based on the updated URL

Exploring ajax for the first time and having some issues. Currently, I am retrieving text from files based on the URL. This is how it's set up: var home_url = "blahblah/index.html#home"; var test_url = "blahblah/index.html#test"; $(document).on("c ...

Steps for generating a PDF using the content of an Angular view

I am working with an Angular app that utilizes ngx-charts to display graphs like the one shown below: https://i.sstatic.net/8kQef.png My current goal is to export this view, along with its graphs, to a PDF file. However, I am unsure about the best approa ...

Receiving a "Maximum call exceeded" error when using Vue.js router guards for the beforeEach hook

As I work on my Firebase-VueJS app, I am implementing basic security rules with router guards. In my main.js file, I have added the following code to handle permissions based on the user's authentication status. However, I encounter an error 'vue ...