GithubHelp home page GithubHelp logo

timdeschryver / ngrx-immer Goto Github PK

View Code? Open in Web Editor NEW
114.0 1.0 6.0 49 KB

Immer wrappers around NgRx methods createReducer, on, and ComponentStore

Home Page: https://www.npmjs.com/package/ngrx-immer

License: MIT License

JavaScript 3.21% TypeScript 96.79%
angular ngrx immer state

ngrx-immer's Introduction

ngrx-immer

Immer wrappers around NgRx methods to simplify mutating state

Installation

npm install ngrx-immer

Do not forget to install immer

Functions

createImmerReducer (@ngrx/store)

Creates an NgRx reducer, but allows you to mutate state without having to use to spread operator.

  • Use it when you want to go Immer all the way
  • Caveat, you have to return the state with each on method
import { createImmerReducer } from 'ngrx-immer/store';

const todoReducer = createImmerReducer(
	{ todos: [] },
	on(newTodo, (state, action) => {
		state.todos.push({ text: action.todo, completed: false });
		return state;
	}),
	on(completeTodo, (state, action) => {
		state.todos[action.index].completed = true;
		return state;
	}),
);

immerOn (@ngrx/store)

Creates an NgRx reducer, but allows you to mutate state without having to use to spread operator.

  • Use it when you want to go sprinkle a little bit of Immer for more complex cases
import { immerOn } from 'ngrx-immer/store';

const todoReducer = createReducer(
	{ todos: [] },
	on(newTodo, (state, action) => {
		return {
			...state,
			todos: [...state.todos, action.todo],
		};
	}),
	immerOn(completeTodo, (state, action) => {
		state.todos[action.index].completed = true;
	}),
);

ImmerComponentStore (@ngrx/component-store)

Wraps Immer around the Component Store updater and setState methods.

import { ImmerComponentStore } from 'ngrx-immer/component-store';

@Injectable()
export class MoviesStore extends ImmerComponentStore<MoviesState> {
	constructor() {
		super({ movies: [] });
	}

	readonly addMovie = this.updater((state, movie: Movie) => {
		state.movies.push(movie);
	});
}

immerPatchState (@ngrx/signals)

Important

Because @ngrx/signals is in developer preview, the immerPatchState function is also in developer preview. It is ready to try, but may change before becoming stable.

Provides an Immer-version of the patchState function from the @ngrx/signals package. In addition to partial state objects and updaters that update the state immutably, it accepts updater functions that update the state in a mutable manner. Similar to patchState, the immerPatchState function can be used to update the state of both SignalStore and SignalState.

const UserStore = signalStore(
	withState({
		user: { firstName: 'Konrad', lastName: 'Schultz' },
		address: { city: 'Vienna', zip: '1010' },
	}),
	withMethods((store) => ({
		setLastName(lastName: string): void {
			immerPatchState(store, (state) => {
				state.user.lastName = lastName;
			});
		},
		setCity(city: string): void {
			immerPatchState(store, (state) => {
				state.address.city = city;
			});
		},
	}))
);

Please note, that the updater function can only mutate a change without returning it or return an immutable state without mutable change.

This one is going to throw a runtime error:

// will throw because of both returning and mutable change
immerPatchState(userStore, (state) => {
	state.name.lastname = 'Sanders'; // mutable change
	return state; // returning state
});

immerReducer

Inspired by Alex Okrushko, immerReducer is a reducer method that uses the Immer produce method. This method is used by all the methods in ngrx-immer provides.

FAQ

Resources

ngrx-immer's People

Contributors

preda7or avatar rainerhahnekamp avatar timdeschryver avatar yevit avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

ngrx-immer's Issues

LICENSE

I found your package when I use Ngrx. It is so useful.
But I don't see any license in your source code on Github.
For an official project to consume, Could you add a license? Thanks

Problem after update ngrx/store to version 11

issue
While above code work correctly with ngrx version 10
After update ngrx/store to version 11 immerOn() doesn't know the type of state.
In this case it return state as unknow type.

Cannot assign to read only property

Here is my state and reducer:
`export interface AppState {
hexMatrix: HexMatrixState;
}

export interface HexMatrixState {
hexLines: HexLine[];
}

export const initialState: HexMatrixState = {
hexLines: [],
};

export const hexMatrixReducer = createReducer(
initialState,
immerOn(loadHexMatrix, (state, action) => {
state.hexLines = [...action.hexMatrix.hexLines];
return state;
}),
immerOn(updateHex, (state, action) => {
state.hexLines[action.hexCoordenates.line].hexes[
action.hexCoordenates.column
].hexType = action.hexType;
return state;
})
);`

When I try to execute "updateHex" action I got this error: "ERROR TypeError: Cannot assign to read only property 'hexType' of object '[object Object]'"

Here is the complete stacktrace:
hex-matrix-facade.ts:27 ERROR TypeError: Cannot assign to read only property 'hexType' of object '[object Object]' at hex-matrix.reducer.ts:30:7 at ngrx-immer-shared.mjs:9:42 at Immer2.produce (immer.mjs:570:20) at ngrx-immer-shared.mjs:9:16 at ngrx-store.mjs:1682:22 at combination (ngrx-store.mjs:345:31) at ngrx-store.mjs:1108:23 at ngrx-store.mjs:375:14 at computeNextEntry (ngrx-store-devtools.mjs:506:17) at recomputeStates (ngrx-store-devtools.mjs:536:48)

Lifecycle Hooks

Hello,

I have a problem with the lifecycle hooks of ngrx on component stores.
I am using ImmerComponentStore to create a store for a component and I want to use the OnStateInit hooks.
The guide of NgRx says that I need to provide the store with provideComponentStore, but whenever I do this for a ImmerComponentStore , I get this error:

Error: immer.component.ts:14:37 - error TS2345: Argument of type 'typeof ImmerStore' is not assignable to parameter of type 'Type<ComponentStore<object>>'.
  Construct signature return types 'ImmerStore' and 'ComponentStore<object>' are incompatible.
    The types of 'updater' are incompatible between these types.
      Types of parameters 'updaterFn' and 'updaterFn' are incompatible.
        Type 'object' is not assignable to type 'void | MeetingState'.

14   providers: [provideComponentStore(ImmerStore)],

@Component({
  // ... other
  providers: [
    provideComponentStore(ImmerStore)
  ]
})

Update to NGRX 14

Thanks for the great library!

I was wondering if there were plans for upgrading to NGRX version 14?
I saw it was already updated in the 'package.json' but it still isn't published.

Missing store and component-store directories from 2.1.0

Hi,

I've just updated to 2.1.0 and the store and component-store folders seem to be missing

Heres 2.0.1
image

and here 2.1.0
image

as a result I can't import the store, for example:
image

I'm guessing the build update has caused this? I don't think its related to the PR I've just done but let me know if it is πŸ˜•!

Considering release a new version with license file?

Hi, I see you add a license file because of this issue #2.

That's really great!

But when I'm trying to install the latest version(v0.0.5) in npm, I found the final package missing the license file. So, could we release a new version to include the license file?

Anyway, thanks very much~

source code is not up to date?

Hi, I really appreciate the lib you create~~

However, as the title said, it seems the source code isn't consistent with the version published in the npm? I guess you forget pushing?

Anyway, thanks for your creation~

The automated release is failing 🚨

🚨 The automated release from the main branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

The automated release is failing 🚨

🚨 The automated release from the main branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry http://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Investigate ability to split ngrx-immer into: ngrx-immer-signals, ngrx-immer-store, ngrx-immer-component-store

First of all, thank you for your great work!

I have a question regarding the usage of your library. What if I only require the signals and store functionalities and do not want to install "@ngrx/component-store"? It's not necessary for my project and won't be utilized. I prefer to keep my dependencies clean.
For now I getting error:

Could not resolve "@ngrx/component-store"

node_modules/ngrx-immer/fesm2022/ngrx-immer-component-stone.mjs:3:54:
3 | import { ComponentStore, provideComponentStore} from '@ngrx/component-store';

Could you please advise me on how to achieve this with the current version of your library? If it's not possible at the moment, could we consider splitting the library into three smaller ones to match directly to my requirements?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.