Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered:

Below is my code snippet:

import { combineReducers, createStore } from 'redux';
import produce from 'immer';

const mainReducer = produce(async (draft, { type, payload }: { type: string; payload: any }) => {
    switch (type) {
        case 'foo': {
            draft = await myAsyncFn(payload);
        }
    }
});

const reducers = {
    main: mainReducer,
};

const rootReducer = combineReducers(reducers);

export const mainStore = createStore(rootReducer);

The output shows the following error message:

Error: [Immer] produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '[object Promise]'

Question arising - why doesn't it work despite the assumption of its possibility as per this reference link: ?

What does the term

classes that are marked with '[immerable]
entail exactly?

Answer №1

Although Immer allows for writing asynchronous logic within the produce function, it is important to note that asynchronous logic should never be included in a Redux reducer.

The error mentioned specifically occurs because Immer is designed to update plain JavaScript objects and arrays by default. To update a class instance or similar data structure, you must include a special immerable symbol in that specific class type.

It is recommended to use Immer with Redux, especially when utilizing the official Redux Toolkit package, which seamlessly integrates Immer into its createSlice API.

Answer №2

While using redux-toolkit, I encountered an error that arose after changing the type of the state to a generic typescript type in the createSlice() method. The error was not present before this modification.

import { AsyncState } from "./AsyncState";

export class SliceState<T> {
  constructor(initialState: T) {
    this.data = initialState;
    this.status = new AsyncState();
  }
  status: AsyncState;
  data: T;
}

The additional error message indicated: [Immer] produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. The current object received: '[object Object]'

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

Developing an npm console application that is "installable" similar to tools like yeoman, gulp, or grunt

Recently dipping my toes into the world of NPM, I've been itching to create a package that functions as a console app (think gulp and grunt). My goal is simple: I want users to be able to run npm install -g mypackage followed by mypackage This sh ...

How to transfer data between components in Angular 6 using a service

I'm facing an issue with passing data between the course-detail component and the course-play component. I tried using a shared service and BehaviorSubject, but it didn't work as expected. Strangely, there are no errors thrown, and the data remai ...

What's the best way to transfer a variable from a PHP file to a jQuery AJAX file so that it can be used as the URL parameter when sending

I am just starting out with javascript, jquery, and ajax. Unfortunately, I've encountered an issue where my code is not working as expected. Below, you can find a detailed description of my code and the problem at hand. If someone could offer some ass ...

Integrate retrieved JSON data using Ajax into D3 visualizations

Could someone please guide me on how to incorporate fetched JSON data using Ajax into D3? I've integrated this example here into my project and now I just want to populate the radial layout with my own data. The image below shows the current bilevel r ...

There seems to be an issue with the type error regarding the return of the mysql2/promise

As I delve into using the mysql2/promise library with Typescript, I've encountered a puzzling issue regarding the return type of the query method. Despite my best efforts, I can't seem to resolve an error in my code. Here is a snippet from my c ...

Error: Unable to assign values to undefined properties (specifically 'styles') when using withLess, withSass, or withCSS in next.config.js within Next.js

I have been attempting to set up a NextJS 12 project with custom Ant Design. Following some examples I found, it seems I need to configure my next.config.js file with the libraries @zeit/next-sass, @zeit/next-less, and @zeit/next-css. However, when I try t ...

jQuery tipsy not triggering click event in Internet Explorer

Hey there! I've been using the jquery tipsy plugin for displaying colour names above colour swatch images. One thing I'm trying to do is trigger a checkbox to be checked/unchecked when a user clicks on the image. $(document).ready(function(){ ...

External Submit button malfunctioning when attempting to submit two distinct forms

I'm currently working on a program to add items to the cart, and I need to include product attributes like colors and sizes in the process. However, I seem to be encountering an issue where only one form is submitted when using jQuery's submit(), ...

What are the best practices for running node in VSCode?

$ node test.js internal/modules/cjs/loader.js:883 throw err; ^ I have exhausted all possible solutions, including checking the PATH route for Node.js, restarting, and using different files. Despite the fact that I am able to retrieve the version when ...

Refresh a selection menu using a checkmark

Can you help me with a script to enable/disable a dropdown based on the checkbox status? <body onload="enableDropdown(false);"> <form name="form1" method="post" onload="enableDropdown(false);"> <input type="checkbox" name="others" oncl ...

The isotope plugin import failed, displaying the error message "The function $(container).isotope does not exist."

I've been struggling to get the Metafizzy Isotope plugin to work, but I'm having no success. The Network tab indicates that it's not loading properly. After installing isotope-layout and requiring it in my main-file.js, the code still doesn ...

Issue 2339: Dealing with || and Union Types

I've encountered an interesting issue while working with TypeScript and JavaScript. I created a code snippet that runs perfectly in JavaScript but throws a syntax error in TypeScript. You can check it out in action at this TypeScript Sandbox. Essenti ...

Tips for returning an element to its starting position following animation

Hey there, I’m fairly new to the world of HTML and CSS. Recently, I was working on creating a YouTube clone website and I’ve run into an issue with the navigation. On the official YouTube website, when you click on the hamburger menu icon, the naviga ...

Accessing the locally stored data and displaying it in ng-bind

My journey to learn javascript through this project has hit a roadblock. I have stored an exchange rate in local storage: localStorage.gbpUSD = "1.42746"; Now, I want to utilize it instead of the hardcoded exchange rate in the code below... <input t ...

Display only specific PHP-encoded JSON data in a formatted table

After receiving a variable from PHP, I convert it to JSON as shown below: var myData = <?php echo json_encode($json_array) ?>; When I log the output, it looks something like this: 0: Carat: "0.70" Clarity: "VVS2" Color: "D" Cut: "Very Good" Polish ...

Emulate the selection process using element-ui and vue-test-utils

During my unit tests using Jest and Element-ui in Vue, I encountered an issue with a component containing a select element with 2 options. After selecting an option from the dropdown, I needed to verify that a specific action was called. 1) Everything wor ...

Would you be able to clarify why the run() function is giving me an error when I try to return {1,3}, but it works fine when I return {a,b} in

I'm really confused as to why the return {1,3} in the run() function is throwing an error when it works just fine for return {a,b} in the fun() function function fun(){ let a = 10; let b = 20; return {a, b}; } ...

Challenges with incrementing in Jquery's each loop and setTimeout

http://jsfiddle.net/fxLcy/ - an example showcasing the use of setTimeout. http://jsfiddle.net/fxLcy/1/ - this demo does not include setTimeout. Although all elements are correctly positioned, I am in need of that delayed animation =/ My goal is to arrang ...

Exploring the method to deactivate and verify a checkbox by searching within an array of values in my TypeScript file

I am working on a project where I have a select field with checkboxes. My goal is to disable and check the checkboxes based on values from a string array. I am using Angular in my .ts file. this.claimNames = any[]; <div class="row container"> ...

React function components will trigger a re-render when there is any change

I am feeling overwhelmed by all this new React stuff. I never encountered these issues when working with class components in React Native before. There must be something I'm missing here because I'm also facing similar problems with another compo ...