React does not update values nor state - reactjs

No matter what i write, even if i write a variable and push into it and console.log that value inside filterColumns function it still does not give an updated value nor for the simple variable nor for the state,
console.log(filteringItems) inside filterColumns gives just property value but inside addFilteringItem function it just logs initial state value, can't even think of what is wrong with the code, if you have any additional questions i'll answer any of them.
import { GridColumnsConfig } from './GridColumnsConfig/GridColumnsConfig';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import React, { useEffect, useState } from "react";
import { IOptionsData } from "./Grid";
interface IGridDropdownItemProps {
options: IOptionsData;
filterRequest: any;
cancelFilter?: any;
// filterRequest: (data: IDataRecords) => () => () => void; #comehere
}
function GridDropdownItem(props: IGridDropdownItemProps) {
let id: number = Math.ceil(Math.random() * 1000000000000);
const [filteringItems, setFilteringItems] = useState([...props.options.columns]);
const addFilteringItem = (name:string) => {
let temp = filteringItems.map((item) =>{
if(item.name === name){
item.visible = !item.visible;
}
return item;
});
setFilteringItems([...temp]);
};
const filterColumns = () => {
let columns = [...filteringItems];
// add all column name by default
let data: {
columns: any[];
limit: number;
page: number;
} = {
columns: columns,
limit: props.options.limit,
page: props.options.page,
};
let tempColumns = [
...columns.filter(
(col) =>
Object.entries(columns).filter(
(fi) => fi[0] === col.name && fi[1] === false
).length > 0
),
];
columns.map((col) => {
col.visible = true;
delete col.filter.value;
});
// tempColumns changes part of columns(bcs of pointer) that changes data.columns(bcs of pointer too)
tempColumns.map((col) => {id
col.visible = false;
col.filter.value = null;
});
// console.log(columns, tempColumns);
props.filterRequest(data);
};
return (
<div className="single-button-dropdown uib-dropdown-menu nt-scroll custom-dropdown btn-block old-dropdown-styles ">
<ul
className="dropdown-block scroll vertical hard"
style={{ width: "100%" }}
>
<li>
<DndProvider backend={HTML5Backend}>
<GridColumnsConfig columns={filteringItems} handleCheckboxClick={addFilteringItem}/>
</DndProvider>
</li>
</ul>
<div style={{ position: "absolute", zIndex: 1 }} className="buttons">
<div className="actions">
<div className="pull-right">
<button
type="button"
className="btn btn-primary"
onClick={() => {
filterColumns();
props.cancelFilter();
}}
>
Submit
</button>
{props.options.compactMenu !== undefined &&
props.options.compactMenu ? (
<button
type="button"
className="btn btn-primary"
style={{ background: "#ff8518", color: "#fff" }}
ng-click="saveGridState()"
>
Save
</button>
) : (
<button
className="nd btn btn-default"
onClick={() => props.cancelFilter()}
>
Close
</button>
)}
</div>
</div>
</div>
</div>
);
}
export default GridDropdownItem;

Getting tired really blurred my vision, problem is in mutation.
I'm directly mutating props and that was setting my state to prop value again and again.
let temp = filteringItems.map((item) =>{
if(item.name === name){
item.visible = !item.visible;
}
return item;
});
Fixed Code
let temp = props.options.columns.map((item) =>{
if(item.name === name){
return {...item,visible:!item.visible}
}
return item;
});

Related

Update one element of big list without re render others elements in react hooks?

i want to optimize my react App by testing with a large list of li
Its a simple todo List.
By exemple, when click on a li, task will be line-through, and check icon will be green. This simple action is very slow with a large list because, the whole list is re render.
How to do this with React Hooks?
function App() {
const [list, setList] = useState([]);
const [input, setInput] = useState("");
const inputRef = useRef(null);
useEffect(() => inputRef.current.focus(), []);
//Pseudo Big List
useEffect(() => {
const test = [];
let done = false;
for (let i = 0; i < 5000; i++) {
test.push({ task: i, done });
done = !done;
}
setList(test);
}, []);
const handlerSubmit = (e) => {
e.preventDefault();
const newTask = { task: input, done: false };
const copy = [...list, newTask];
setList(copy);
setInput("");
};
const checkHandler = (e, index) => {
e.stopPropagation();
const copy = [...list];
copy[index].done = !copy[index].done;
setList(copy);
};
const suppression = (e, index) => {
e.stopPropagation();
const copy = [...list];
copy.splice(index, 1);
setList(copy);
};
const DisplayList = () => {
return (
<ul>
{list.map((task, index) => (
<Li
key={index}
task={task}
index={index}
suppression={suppression}
checkHandler={checkHandler}
/>
))}
</ul>
);
};
//JSX
return (
<div className='App'>
<h1>TODO JS-REACT</h1>
<form id='form' onSubmit={handlerSubmit}>
<input
type='text'
placeholder='Add task'
required
onChange={(e) => setInput(e.target.value)}
value={input}
ref={inputRef}
/>
<button type='submit'>
<i className='fas fa-plus'></i>
</button>
</form>
{list.length === 0 && <div id='noTask'>No tasks...</div>}
<DisplayList />
</div>
);
}
export default App;
Li component
import React from "react";
export default function Li(props) {
return (
<li
onClick={(e) => props.checkHandler(e, props.index)}
className={props.task.done ? "line-through" : undefined}
>
{props.task.task}
<span className='actions'>
<i className={`fas fa-check-circle ${props.task.done && "green"}`}></i>
<i
className='fas fa-times'
onClick={(e) => props.suppression(e, props.index)}
></i>
</span>
</li>
);
}
CodeSandbox here: https://codesandbox.io/s/sad-babbage-kp3md?file=/src/App.js
I had the same question, as #Dvir Hazout answered, I followed this article and made your code the changes you need:
function App() {
const [list, setList] = useState([]);
const { register, handleSubmit, reset } = useForm();
//Pseudo Big List
useEffect(() => {
const arr = [];
let done = false;
for (let i = 0; i < 20; i++) {
arr.push({ id: uuidv4(), task: randomWords(), done });
done = !done;
}
setList(arr);
}, []);
const submit = ({ inputTask }) => {
const newTask = { task: inputTask, done: false, id: uuidv4() };
setList([newTask, ...list]);
reset(); //clear input
};
const checkHandler = useCallback((id) => {
setList((list) =>
list.map((li) => (li.id !== id ? li : { ...li, done: !li.done }))
);
}, []);
const suppression = useCallback((id) => {
setList((list) => list.filter((li) => li.id !== id));
}, []);
//JSX
return (
<div className="App">
<h1>TODO JS-REACT</h1>
<form onSubmit={handleSubmit(submit)}>
<input type="text" {...register("inputTask", { required: true })} />
<button type="submit">
<i className="fas fa-plus"></i>
</button>
</form>
{list.length === 0 && <div id="noTask">No tasks...</div>}
<ul>
{list.map((task, index) => (
<Li
key={task.id}
task={task}
suppression={suppression}
checkHandler={checkHandler}
/>
))}
</ul>
</div>
);
}
Li component
import React, { memo } from "react";
const Li = memo(({ task, suppression, checkHandler }) => {
// console.log each time a Li component re-rendered
console.log(`li ${task.id} rendered.`);
return (
<li
onClick={(e) => checkHandler(task.id)}
className={task.done ? "line-through" : undefined}
>
{task.task}
<span className="actions">
<i className={`fas fa-check-circle ${task.done && "green"}`}></i>
<i className="fas fa-times" onClick={(e) => suppression(task.id)}></i>
</span>
</li>
);
});
export default Li;
You can check it live here
I know it's probably late for your question, but may help others ;)
You can use React.memo and wrap the Li component. This will cache the instances of the Li component based on shallow comparison. Read more in the docs
Otherwise, if you don't need the state in the container, you can keep it locally in the Li component and then it won't cause a whole list rerender.

How to push data into object

I am trying to push the {database, id} to the end of the databaseChanges object which will be stored in a state variable as I want to access all of them. However I am getting undefined when I try to set it a new state variable (setDatabaseArr).
Here is my code:
const UnitTestsDatabaseView = props => {
const [databaseArr, setDatabaseArr] = useState('')
const addToProduction = test => () => {
const databaseChanges = props.unitTestsData.map(test => {
return {
"unit_test_id": test.id,
"databases": test.databases
}
})
const { databases, id } = test
console.log(databases, id)
databaseChanges.push(databases, id)
setDatabaseArr(databases, id)
console.log( setDatabaseArr(databases, id))
console.log( databaseChanges.push(databases, id))
}
return (
<div>
<div className='Card' style={{marginTop: '40px', overflow: 'hidden'}}>
<div className='TableTopbar UnitTestsGrid'>
<div>ID</div>
<div>Name</div>
<div>Database</div>
<div />
</div>
{props.unitTestsData && props.unitTestsData.map(test =>
<div key={test.id} className='Table UnitTestsGrid' style={{overflow: 'hidden'}}>
<div>{test.id}</div>
<div>{test.unit_test_name}</div>
<div>{test.databases}
<div>
<Checkbox
mainColor
changeHandler={addToProduction(test)}
data={{}}
id={test.id}
/>
</div>
</div>
</div>
)}
</div>
</div>
)
}
export default withRouter(UnitTestsDatabaseView)
I review your code, It seems there is a problem with the implementation on how to push a value to the state.
I tried to reproduce the problem and try to implement of which I think a solution.
And here is the code
import React, { useState, useEffect } from "react";
import { Checkbox } from "#material-ui/core";
// In order to reproduce the propblem
// Lets that these are the values of the unitTestsData props
// and instead of passing this as value of a props
// I defined it right here.
const unitTestsData = [
{ id: 1, unit_test_name: "Unit I", databases: "test1" },
{ id: 2, unit_test_name: "Unit II", databases: "test2" },
{ id: 3, unit_test_name: "Unit III", databases: "test3" }
];
const UnitTestsDatabaseView = () => {
const [databaseArr, setDatabaseArr] = useState([]);
// Maybe you want to push data if the checkbox is checked
// and pop the data if checkbox is unchecked :: Yes ???
// This is how you do it.
const addToProduction = ({ target }, { id, databases }) => {
setDatabaseArr((previousState) => {
let newState = [...previousState];
if (target.checked) {
newState = [
...newState,
{ unit_test_id: newState.length + 1, databases }
];
} else {
const i = newState.findIndex(({ unit_test_id }) => unit_test_id === id);
if (i !== -1) newState.splice(i, 1);
}
return newState;
});
};
useEffect(() => {
console.log("databaseArr", databaseArr);
}, [databaseArr]);
return (
<div>
<div className="Card" style={{ marginTop: "40px", overflow: "hidden" }}>
<div className="TableTopbar UnitTestsGrid">
<div>ID</div>
<div>Name</div>
<div>Database</div>
</div>
{unitTestsData.map((test) => {
const { id, unit_test_name, databases } = test;
return (
<div
key={id}
className="Table UnitTestsGrid"
style={{ overflow: "hidden" }}
>
<div>{id}</div>
<div>{unit_test_name}</div>
<div>
{databases}
<div>
<Checkbox
color="secondary"
onChange={(e) => addToProduction(e, test)}
data={{}}
id={id.toString()}
/>
</div>
</div>
</div>
);
})}
</div>
</div>
);
};
export default UnitTestsDatabaseView;
You may click the codesandbox link to see the demo
https://codesandbox.io/s/pushing-value-49f31

React API call in componentDidMount, and componentWillReceiveProps (order confusion)

I'm fairly new to React and Redux. I'm having this issue where the ratings sometimes don't show up when I refresh the page (please see screenshot). I think it's because sometimes the user from Redux comes into componentWillReceiveProps before loadTeamsData executes, but I don't know why that would make ratings not show up. (Also, I feel like my code is crap... Any critic is appreciated!)
Home.js
export class Home extends React.Component {
state = {
upVote: null,
downVote: null,
clickedTeam: "",
teams: teams
};
// When component mounted, add in thumbUp & thumbDown properties to each team
componentDidMount() {
const { user } = this.props.auth;
console.log("didmount");
this.loadTeamsData();
// Stores user voting info to state when coming from a different page
if (user) {
if (!(Object.entries(user).length === 0)) {
console.log("user", user, user.upVote, user.downVote);
this.setState({
upVote: user.upVote,
downVote: user.downVote
});
}
}
}
// Loads teams thumbUp, thumbDown data to state
loadTeamsData = () => {
axios.get("/api/teams/").then(res => {
console.log("data", res.data);
this.setState({
teams: this.state.teams.map(team => {
res.data.map(vote => {
if (vote.id === team.id) {
team.thumbUp = vote.thumbUp;
team.thumbDown = vote.thumbDown;
}
return vote;
});
return team;
})
});
});
};
// When props from Redux come in, set the state
UNSAFE_componentWillReceiveProps(nextProps) {
const { user } = nextProps.auth;
if (user !== this.props.auth.user && user) {
console.log("willreceiveprops", `\n`, this.props.auth.user, user);
this.setState({
upVote: user.upVote,
downVote: user.downVote
});
}
}
// Handle click on thumbs
onClickHandler = (id, e) => {
const { alert } = this.props;
const up = e.target.classList.contains("up");
if (this.props.auth.isAuthenticated) {
if (up && this.state.upVote === "") {
if (id === this.state.downVote) {
alert.error("You cannot up vote and down vote the same team!");
} else {
this.props.update_up(id);
this.setState(prevState => {
return {
teams: prevState.teams.map(team => {
if (id === team.id) {
team.thumbUp = team.thumbUp + 1;
team.votedUpColor = { color: "#1E95E0" };
}
return team;
}),
clickedTeam: id,
upVote: id
};
});
alert.show(`You Up Voted ${id}`);
}
} else if (!up && this.state.downVote === "") {
if (id === this.state.upVote) {
alert.error("You cannot up vote and down vote the same team!");
} else {
this.props.update_down(id);
this.setState(prevState => {
return {
teams: prevState.teams.map(team => {
if (id === team.id) {
team.thumbDown = team.thumbDown + 1;
team.votedDownColor = { color: "#F8004C" };
}
return team;
}),
clickedTeam: id,
downVote: id
};
});
alert.show(`You Down Voted ${id}`);
}
} else {
alert.show("You have already voted.");
}
} else {
alert.show("Please log in first!");
this.props.history.push(`/login`);
}
};
// When user votes, update the db before updating the state
UNSAFE_componentWillUpdate(newProps, newState) {
newState.teams.map(team => {
if (team.id === newState.clickedTeam) {
axios.put(`/api/teams/${newState.clickedTeam}/`, {
id: team.id,
thumbUp: team.thumbUp,
thumbDown: team.thumbDown
});
}
});
}
render() {
// Welcome header message when user logs in
console.log("render", this.state.teams[0].thumbUp);
const { isAuthenticated, user } = this.props.auth;
const { upVote, downVote } = this.state;
const welcome_header = (
<div className="welcome-header">
<h4 style={{ textAlign: "left" }} className="welcome-header-line">
Welcome, {user && user.username}!
</h4>
<h4 style={{ textAlign: "left" }} className="welcome-header-line">
<span>
Your Vote:{" "}
<i className="far fa-thumbs-up up" style={{ color: "#1E95E0" }}></i>
<span style={{ textTransform: "capitalize" }}>{upVote}</span>
</span>{" "}
<span>
<i
className="far fa-thumbs-down down"
style={{ color: "#F8004C" }}
></i>
<span style={{ textTransform: "capitalize" }}>{downVote}</span>
</span>
</h4>
</div>
);
return (
<div className="home">
<div className="home-container">
{isAuthenticated && welcome_header}
<h2>Who Is Your NBA Champion This Year?</h2>
<Teams
upVote={this.state.upVote}
downVote={this.state.downVote}
teams={this.state.teams}
onClickHandler={this.onClickHandler}
/>
</div>
</div>
);
}
}
Home.propTypes = {
update_up: PropTypes.func.isRequired,
update_down: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(mapStateToProps, { update_up, update_down })(
withAlert()(withRouter(Home))
);
When ratings show up
When ratings don't show up
I'm console logging this.state.teams[0] and this.state.teams[0].thumbUp in the render method.
Even during the first render, both thumbUp and thumbDown show in this.state.teams[0], but this.state.teams[0].thumbUp appears to be undefined.
I happened to fix the issue. The issue was actually in the Rating.js file, sorry that I didn't post that file cuz I thought the issue had to be in Home.js.
Before, in Rating.js file, I originally brought in user from redux which caused the issue (I believe it didn't make Rating re-render when in Home.js the axios get call happened after componentWillReceiveProps).
After, instead of bringing in user from redux, I passed user to Rating.js as a prop from Home.js.
Even though it works fine now, I still don't know what exactly the issue was... I'd much appreciate it if someone could enlighten me! Also, please critique my code (i.e. where I can improve)! THANK YOU!
Rating.js (Before)
import React from "react";
import "./Rating.css";
import PropTypes from "prop-types";
import { connect } from "react-redux";
const Rating = props => {
const { thumbUp, thumbDown, id, votedUpColor, votedDownColor } = props.team;
const { upVote, downVote, onClickHandler } = props;
const { user } = props.auth;
let thumbUpColor =
user && id === upVote ? { color: "#1E95E0" } : votedUpColor;
let thumbDownColor =
user && id === downVote ? { color: "#F8004C" } : votedDownColor;
console.log(id, thumbUp, thumbDown);
return (
<div className="rating" key={id}>
<button
className="thumb-up up"
style={thumbUpColor}
onClick={e => onClickHandler(id, e)}
>
<i className="far fa-thumbs-up up"></i>
<span style={{ userSelect: "none" }} className="up">
{thumbUp}
</span>
</button>
<button
className="thumb-down down"
style={thumbDownColor}
onClick={e => onClickHandler(id, e)}
>
<i className="far fa-thumbs-down down"></i>
<span style={{ userSelect: "none" }} className="down">
{thumbDown}
</span>
</button>
</div>
);
};
Rating.propTypes = {
team: PropTypes.object.isRequired,
onClickHandler: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(mapStateToProps)(Rating);
Rating.js (After)
import React from "react";
import "./Rating.css";
import PropTypes from "prop-types";
// import { connect } from "react-redux";
const Rating = props => {
const { thumbUp, thumbDown, id, votedUpColor, votedDownColor } = props.team;
const { upVote, downVote, onClickHandler, user } = props;
// const { user } = props.auth;
let thumbUpColor =
user && id === upVote ? { color: "#1E95E0" } : votedUpColor;
let thumbDownColor =
user && id === downVote ? { color: "#F8004C" } : votedDownColor;
console.log(id, thumbUp, thumbDown);
return (
<div className="rating" key={id}>
<button
className="thumb-up up"
style={thumbUpColor}
onClick={e => onClickHandler(id, e)}
>
<i className="far fa-thumbs-up up"></i>
<span style={{ userSelect: "none" }} className="up">
{thumbUp}
</span>
</button>
<button
className="thumb-down down"
style={thumbDownColor}
onClick={e => onClickHandler(id, e)}
>
<i className="far fa-thumbs-down down"></i>
<span style={{ userSelect: "none" }} className="down">
{thumbDown}
</span>
</button>
</div>
);
};
Rating.propTypes = {
team: PropTypes.object.isRequired,
onClickHandler: PropTypes.func.isRequired
// auth: PropTypes.object.isRequired
};
// const mapStateToProps = state => ({
// auth: state.auth
// });
export default Rating;

having trouble seeing increment button in react component

I have two componenets , counter and counters. I have a box that shows the value when you click the increment button in my counter component thats not being displayed. I refactored my code so that that my counter component is a controlled component instead of an uncontrolled component so it gets its data from my props object. I will paste the code down below.
Update: I am now able to see the box that has the number of increments but when i click Increment I get Nan displayed in the box for the value.
counter component
import React, { Component } from "react";
class Counter extends Component {
// styles for our bootstrap
styles = {
fontSize: 30,
fontWeight: "bold"
};
render() {
console.log("props", this.props);
return (
<div>
<span className={this.getBadgeColor()}>{this.formatCount()}
</span>
<button
onClick={() => this.props.onIncrement(this.props.counter)}
className="btn btn-secondary btn-md"
>
Increment
</button>
<button
onClick={() => this.props.onDelete(this.props.counter.id)}
className="btn btn-danger btn-sm m-2"
>
Delete
</button>
</div>
);
}
getBadgeColor() {
let classes = "badge m-2 badge-";
classes += this.props.counter.value === 0 ? "warning" :
"primary";
return classes;
}
formatCount() {
const { value } = this.props.counter;
return value === 0 ? <h2> Zero </h2> : value;
}
}
export default Counter;
counters component
import React, { Component } from "react";
import Counter from "./counter";
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 5 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 }
]
};
handleDelete = counterId => {
const counters = this.state.counters.filter(c => c.id !==
counterId);
this.setState({ counters });
};
handleReset = () => {
const counters = this.state.counters.map(c => {
c.value = 0;
return c;
});
this.setState.counters = { counters };
};
handleIncrement = counter => {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counters };
counters[index].value++;
this.setState({ counters });
};
render() {
return (
<div>
<button
onClick={this.handleReset}
className="btn btn-primary btn-sm m-2"
>
Reset
</button>
{this.state.counters.map(counters => (
<Counter
key={counters.id}
onDelete={this.handleDelete}
counter={counters}
onIncrement={this.handleIncrement}
/>
))}
</div>
);
}
}
export default Counters;
you are seeing NaN because in the counters component you should assign values of state .

I tried to create tabs using react and redux. It works all fine, but I want the next element to get highlighted when I close the previous element

But, I am not able to update the list after deleting the element. NO matter what I change in my reducer, I am not able to update the list that will get reflected in the render method.
My render method :
public render() {
let tablist: any;
let updatedList = this.props.OpenTabs.slice();
divStyle = {
borderBottom: '5px solid white'
};
if (updatedList) {
tablist = updatedList.map((menuitem, index, array) => {
this.handleColors(menuitem)
return (
<div
key={Math.random()}
className='tab-elements'
style={divStyle}
id={menuitem.RoutePath}
onClick={() => this.makeActive(menuitem)}>
<Tab
MenuText={menuitem.MenuText}
IconPath={menuitem.IconPath}
RoutePath={menuitem.RoutePath}
id={menuitem.id}
isActive={menuitem.isActive} />
<span><label onClick={() => this.crossHandler(menuitem, array[index + 1], array[index - 1])} >X</label></span>
</div>
);
});
}
return <div className='top-nav'>
<div className='navbar navbar'>
{/* <button className= 'testButton' onClick={() => this.handleClose("Documents4Action")}>close frame</button>*/}
<div className='navbar-header'>
<Link to="/" onClick={() => { this.handleStateChange(this.props.MainMenuOpen) }}>
<button className='HomeButton'>
<img className='HomeButtonImage' alt='D4ALogo_White' src={String(D4ALogo_White)}></img>
</button>
</Link>
<button className='MenuButton' onClick={() => { this.props.togglemenu() }}>
<img className='MenuButtonImage' alt='HamburgerIcon_White' src={String(HamburgerIcon_White)}></img>
</button>
<div className='tab-position'>
<div className='row'>
{tablist}
</div>
</div>
</div>
</div>
</div>;
}
Method that handles the operation on clicking the close button:
crossHandler(menuitem: any, nextElem: any, prevElem: any) {
if (menuitem !== undefined && nextElem !== undefined) {
this.props.history.push(nextElem.RoutePath);
this.props.removetab(menuitem, nextElem)
}
else {
if (prevElem !== undefined) {
this.props.history.push(prevElem.RoutePath);
this.props.removetab(menuitem, prevElem)
}
else {
this.props.history.push('/');
}
}
}
My reducer from redux:
case 'REMOVE_TAB_ACTION':
const index = state.OpenTabs.map(item =>
item.MenuText).indexOf(action.MenuItemDetails.MenuText);
let updatedList = [
...state.OpenTabs.slice(0, index),
...state.OpenTabs.slice(index + 1),
]
updatedList.map(menu => {
console.log("checking inside the list")
if (menu.MenuText === action.MenuItemNextOrPrevDetails.MenuText) {
menu.isActive = true
}
else {
menu.isActive = false
}
console.log(menu)
});
return {
MainMenuOpen: state.MainMenuOpen,
shoulOverlay: state.shoulOverlay,
MenuItems: state.MenuItems,
SelectedMenuItems: state.SelectedMenuItems,
OpenTabs: updatedList
}
I tried using Object.assign but that did not work either. All my other update methods work great when I use this method, but update after deleting gives me an error. Could anyone please point out where the problem. Any suggestion would be helpful. I cannot use third party libraries, if anyone has any idea of this error please let me know.
... and we have answer: array.map creates new array with modified elements - checking values inside loop we have only proof that change/conditions were right - not returned array.
updatedList = updatedList.map(menu => {
console.log("checking inside the list")
if (menu.MenuText === action.MenuItemNextOrPrevDetails.MenuText) {
menu.isActive = true
} else {
menu.isActive = false
}
console.log(menu)
});
or simpler
updatedList = updatedList.map((menu) => {
menu.isActive = (menu.MenuText === action.MenuItemNextOrPrevDetails.MenuText)
});

Resources