What is the process for updating or pushing state in NgRx?

Need help with updating the state after adding inputVal. Currently, it only works on the first click and throws this error:

Error:

TypeError: Cannot add property 1, object is not extensible

import { createReducer, on } from '@ngrx/store'
import { addTodo } from '../actions/todo.actions'

export const initialState: any[] = []
let test: any[] = []

const _todoReducer = createReducer(
  initialState,
  on(addTodo, (state: any, { inputVal }) => {
    test.push(inputVal)
    state = test
    return state
  })
)

export function todoReducer(state, action) {
  return _todoReducer(state, action)
}

Any suggestions on how to push or update state in NgRx? Or if not possible, what are some workarounds?

Answer №1

When working with NgRx, it is important to note that you cannot directly modify the state. Instead, the reducer will generate a new copy of the state every time changes are made. This means that you cannot simply add test directly to the state.

A possible solution:

const _todoReducer = createReducer(
  initialState,
  on(addTodo, (state: any, { inputVal }) => {
    return [...state, inputVal] // By creating a new array, we can update the state accordingly.
  })
)

Answer №2

Take this scenario into consideration: within your component, make sure to inject the Store by using

constructor(private store:Store){..}

To update the Store, use

this.store.dispatch(addTodo("element"))

However, there is a crucial issue at hand. Your Store must be immutable, meaning you cannot simply reuse the test array in the reducer.

const _todoReducer = createReducer(
  initialState,
  on(addTodo, (state: any, { inputVal }) => {
    return [...state, inputVal]
  })
)

This solution should suffice.

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

Ways to effectively test a custom hook event using Enzyme and Jest: A guide on testing the useKeyPress hook

Looking for guidance on testing a custom hook event called useKeyPress with Enzyme and Jest This is my current custom hook for capturing keyboard events and updating keyPress value: import React, { useEffect, useState } from 'react' const useKe ...

Mutations are not set up in the schema

Having an issue with setting up mutations in my project using npm, apollo server, and typeorm. Every time I attempt to create a mutation, I receive the error message "Schema is not configured for mutations". Searching for solutions has been fruitless as mo ...

Get a document from a NodeJS Server with the help of Express

How can I improve my file downloading functionality in Node.js? Currently, when I try to download a PDF file from the server, the content is displayed as data instead of initiating the download process. I would like it to function similar to how it's ...

Detecting slopes using THREE.js

Can someone please advise on how to properly detect slopes in a car game? I want the car to recognize the slope as such, rather than mistaking it for a collision object. I've been looking everywhere for answers but have yet to come across anything use ...

How can data be shared between two functional child components in a React application?

I've been researching on Google quite a bit on how to transfer props between functional components, but it seems like there isn't much information available (or maybe I'm not using the right keywords). I don't need Redux or globally st ...

JavaScript's utilization of local variables and callback functions enables developers to enhance the

After exploring the information in this particular post, it became evident that my issue was different. While working on creating functions for managing mongoDB GridFS, I encountered a perplexing behavior that I will illustrate through a simplified example ...

Columns that can be resized in a right-to-left (

Whenever I use RTL, the columns behave erratically when resizing... I have implemented colResizable. You can see an example here: http://jsfiddle.net/r0rfrhb7/ $("#nonFixedSample").colResizable({ fixed: false, liveDrag: true, gripInnerHtml: "<d ...

TypeORM's Polymorphic Relationship fails to retrieve data from the parent entity

Currently, I am utilizing https://github.com/bashleigh/typeorm-polymorphic for handling polymorphic relations in my model. There are several models involved: // Device Entity @Entity() @TableInheritance({ column: { type: 'varchar', name: 'ty ...

Steps for executing Mocha tests in a specified sequence

Background Currently, I am developing a Node.js program where I am creating test suites in Mocha using Chai and SinonJS. The program involves a core graphics module that manages access to a node-webgl context. Due to the nature of node-webgl, I want to i ...

Is it possible for an Angular App to function as an authenticated user for a real-time database?

Just a question, no code included. I want to restrict access to reading from RTDB only to authenticated users. However, I don't want every user to have to sign up individually. Instead, I would like to have one login tied to the angular app that auto ...

Monitor changes in the select tag to display the updated value and output

I am new to using jQuery. While I have practiced using native PHP Ajax in the past, I now recognize the need to learn jQuery due to current technological advancements and demands. When the select tag changes, I send the "types" value via POST method to a ...

javascript issue with Q promise not passing complete parameters

I am struggling to pass all three arguments successfully in my promise callback. The issue I'm facing is that only one argument is being received instead of the expected three: var asyncFunction= function(resolve) { setTimeout(function() { ...

Is there a way to send a request before opening a new page that doesn't involve using synchronous XMLHttpRequest on the main thread, which is

With the deprecation of synchronous XMLHttpRequest, I am curious about any potential alternatives to achieve a similar behavior. Non-blocking asynchronous XMLHttpRequests may not always be suitable for specific cases. I am specifically referring to a scen ...

Ways to organize class and interface files within the same namespace in TypeScript

I'm tackling a Typescript query related to namespaces and organizing files. Within a single namespace, I have multiple interfaces and classes that I'd like to separate into individual .ts files. The goal is to then combine these files so that whe ...

Verify the dimensions of the window, either width or height

Is there a way to create a condition that checks for window size based on width and height individually? Currently, using '&&' only checks if both width and height are low. How can this condition be modified to display a message if the width is a ...

What could be causing AJAX to consistently return identical data to the callback function when distinct objects are supplied as arguments?

I am attempting to make two separate calls to an MVC controller. The first call returns a series of data, while the second call returns a partial view. When I check in Firebug, both calls show "success" status. I am trying to utilize a callback function t ...

One way to display GIFs sequentially without preloading them is by using JavaScript

On my website, I'm trying to display five animated gifs sequentially. I want gif2 to appear and start its animation only after gif1 has finished its animation. However, the code I'm using is giving me some unexpected behavior. While it works corr ...

Reference error in Angular 2 typings is not defined

My current challenge involves integrating a 3rd party module into my application using webpack. Here is how I have tried to do it: //package.json "dependencies": { "jsrsasign": "6.1.4" } //custom-typings.d.ts declare module KJUR { module jws ...

Trouble with CSS loading in Node.js with express.static

Currently, I am working on a web project using Node.js and Express. However, I am encountering an issue with my CSS not loading correctly when serving the static files. Despite trying to use express.static, it doesn't seem to be functioning as expecte ...

What is the best way to remove all attributes from one interface when comparing to another?

Consider the following two interfaces: interface A { a: number; b: string; } interface B { b: string; } I am interested in creating a new type that includes all the keys from interface A, but excludes any keys that are also present in interface B. ...