Update the state of object in reducer - javascript

I am new to react js. Here, I do have a functionality where there are three diff rows that can be added or removed. I have a reducer which is like,
const initialState = {
Low: [
{
id: 'L0',
technologyId: 0,
technology: '',
type: '',
count: '',
level: 'EASY'
}
],
Medium: [
{
id: 'M0',
technologyId: 0,
technology: '',
type: '',
count: '',
level: 'Medium'
}
],
High: [
{
id: 'H0',
technologyId: 0,
technology: '',
type: '',
count: '',
level: 'Tough'
}
],
SO, Here, I want to have this as a generic,so, I am trying to add objects on click of the plus and remove on - . So,
Here, I am adding using ,
const tempObj = {
id: tempvar + id,
technologyId: 0,
technology: temp[0].technology,
type: type,
count: '',
level: addtype
}
I create this object now depend upon the addType I add it in that particular array.
I do it using this way,
const addData = [...this.props.lowData[addtype], tempObj];
this.props.addNewTech(addData);
So, Here this ...this.props.lowData[addtype] returns an object not an array, is this the problem ? If yes, It should return an array not the object but how is this returning the object and not an array.
My props.lowData is like ,
an object with three different arrays, I mean same as that of the reducer .,But every time I add it adds that element in the Low array only and not in the medium or high. Can any one help me with this ?

The problem is in the reducer you are only updating the Low property. You need to check what property needs to update. For that you can pass addtype to your action creator like so
this.props.addNewTech({ addData, addtype });
And then in action creator
export function addNewTech(data) {
return {
type: ADD_NEW,
data //is equavalent to data: data (ES6)
}
}
And then in reducer dynamically update the object
case ADD_NEW:
return {
...state,
//here choose the property to be updated dynamically
//replace Low: action.data with below line
[action.data.addtype]: action.data.addData,
error: false,
}
**Note here [action.data.addtype]: action.data.addData we are using computed property names in ES6.

Related

Typeorm bigint type key insertion (NestJs)

i use nestjs/typeorm version 8, mysql version 8.
I've tried to insert bigint type data, which is Auto Generated primary key.
Insertion was perfectly fine but the InsertResult has incorrect key value.
looks like Typeorm attached a '0' end of the id string.
InsertResult {
identifiers: [ { id: '900719950050204930' } ],
generatedMaps: [ { id: '900719950050204930' } ],
raw: ResultSetHeader {
fieldCount: 0,
affectedRows: 1,
insertId: '90071995005020493',
info: '',
serverStatus: 2,
warningStatus: 0
}
}
the correct id is '90071995005020493'
but identifiers and generatedMaps property has '900719950050204930'
It happend when I used 'save()' method too.
the output entity get incorrect key value.
why it happend? how can i fix it...
it's my entity
export class MyEntity{
#PrimaryGeneratedColumn({
name: 'id',
type: 'bigint',
comment: 'id',
})
id: string;
#Column('varchar', {
name: 'header',
default: '',
comment: 'header',
})
header: string;
#Column('varchar', {
name: 'title',
default: '',
comment: 'title',
})
title: string;
}
and insert() method call
const newMyEntity = this.myEntityRepository.create();
newMyEntity.header = '';
newMyEntity.title = '';
const insertResult = await this.myEntityRepository.insert(newMyEntity);

Unable to deep clone [duplicate]

This question already has answers here:
How to Import a Single Lodash Function?
(10 answers)
Closed 1 year ago.
I want to make a copy of an object.
Following that, I plan to modify values within the copy but these
modifications should not affect the original object.
Thus I want to make a clone and presently using lodash's deepClone.
But it keeps throwing the following error:
Error!Object(...) is not a function
There is no function within my object. It is just in following structure.
They are just key values where values are either strings or booleans.
const myOriginalObject {
mainKey : {
isMobile: true,
data: {
id: '',
header: '',
flag: '',
desc1: '',
desc2: '',
logo: {
src: '',
alt: '',
},
img: {
src: '',
alt: '',
},
}
}
}
Just to test it out created a random object as follows.
And even this throws same error.
const myOriginalObject = {
b: '',
c: ''
}
This is the implementation to deep copy. myOriginalObject can be either one of above objects.
import { cloneDeep } from 'lodash/cloneDeep';
const myClone = cloneDeep(myOriginalObject);
What am I doing wrong? Pls advice. Thanks.
UPDATE:
My lodash version from package.json
"lodash": "^4.17.20",
Error:
render had an error: TypeError: Object(...) is not a function
try with this
const myOriginalObject {
mainKey : {
isMobile: true,
data: {
id: '',
header: '',
flag: '',
desc1: '',
desc2: '',
logo: {
src: '',
alt: '',
},
img: {
src: '',
alt: '',
},
}
}
}
const newObj = JSON.parse(JSON.stringify(myOriginalObject));
Now make any changes to newObj it will not reflect to myOriginalObject;

How do I access properties of objects inside another object

I have an api endpoint form where I am getting data like below. How i will access the values title, short_title etc.
blog: {
paginations: true,
isLoading: false,
particularBlog: [],
count: 13,
next: 'http://127.0.0.1:8000/api/blog/all-blog/?page=2',
previous: null,
results: [
{
id: 47,
user: 1,
title: 'adasd',
short_title: 'asd',
publish: '2019-09-16',
slug: 'adasd',
comments_count: 0,
likes_count: 0
},
{
id: 46,
user: 1,
title: 'adasda',
short_title: 'asdas',
publish: '2019-09-16',
slug: 'adasda',
comments_count: 0,
likes_count: 0
}
]
},
what i have done is
<div>{
this.props.blog && Object.keys(this.props.blog).map((key) => {
return <p>{this.props.blog.results[key]}</p>
})
}</div>
but it is giving error stating paginations' of undefined. Can someone please pointout what i am doing wrong here?
Where is what is happening
Object.keys(this.props.blog).map((key) => { is getting the keys of this.props.blog and this.props.blog.results[key] is trying to access the properties of results with the keys of blog.
What you should do is have another .map with Object.keys of this.props.blog.results
OR
What I think you are trying to do is list all properties on the this.props.blog.results array, so here is what you can do
this.props.blog && this.props.blog.results && this.props.blog.results.map(result=> <p>{result.short_title}</p>
You do .map on the results array and display short_title.
blog.results.map(el => (<div>{el.short_title}</div>))

How to modify a specific element of a nested object using ES6?

I have this initialStore:
const initialState =
{
0:{
screen_name: '1',
props: null,
},
1:{
screen_name: '2',
props: null,
},
2:{
screen_name: '3',
props: null,
},
3:{
screen_name: '4',
props: null,
},
4:{
screen_name: '5',
props: null,
},
}
I want to know how can I modify for example the value state.0.screen_name: 1, while keeping the rest of the original state using ES6?
This is the approach that I have so far:
export const navigationReducer = createReducer(initialState, {
[types.CHANGE_SCREEN_EXPERIMENTAL](state,action){
return{...state[action.id], screen_name:action.screen_name, ...state
};
}
},
);
However, that returns this:
The action.id is 0, it should modify the state[0] element, however, it copied its elements, modified them and placed them on the state object itself instead of the state[0] object.
Desired result:
navigationReducer:{
0: {
props: null,
screen_name: "ad"
}
1:Object
2:Object
3:Object
4:Object
}
I do not want the screen_name nor props to be outside those objects (0,1,2,3,4).
Any ideas are well appreciated.
I found the way to do it using ES6
Here is how:
export const navigationReducer = createReducer(initialState, {
[types.CHANGE_SCREEN_EXPERIMENTAL](state,action){
return{
...state,[action.id]:{
...state[action.id],
screen_name:action.screen_name,
props:action.props,
}
};
}
},
);
This results in:
Thank you very much for your help and time #ibrahimmahrir.

UnderscoreJS wont extend object

I am trying to merge 2 objects using underscore. The destination object is a mongoose model but I have applied lean() to it to make it return a javascript object rather than a mongo document.
model.find({}).lean().exec(function (error, object) {});
I then try extending using underscore
_.extend(object, source);
But it only returns the source object.
I have tried with simple objects to test and those worked fine, so I am assuming it has something to do with mongoose?
The simple objects that worked were:
{foo:'foo'},{bar:'bar'}
And the objects that I am trying to merge but haven't been able to are:
{
_id: 526540eaa77883d815000029,
name: 'House',
description: '',
type: 'residential',
cost: 100,
buildTime: 5,
resources: { produces: [], required: { wood: 5 } },
population: { provides: 10, required: 0 },
requires: [],
maxLevel: 5,
upgrades:
{ '2': { resourceMultiplier: 1.2, cost: 150, time: 5 },
'3': { resourceMultiplier: 1.5, cost: 200, time: 7 },
'4': { resourceMultiplier: 2, cost: 300, time: 10 },
'5': { resourceMultiplier: 2.5, cost: 500, time: 15 } },
scale: { x: 1, y: 1, z: 1 }
}
{
empireId: '52654578a4eff60000000001',
buildingId: '526540eaa77883d815000029',
level: 1,
isComplete: false,
isUpgrading: false,
gridId: '175|0|125',
started: 1382442513823,
_id: 526666113fccae68be000003,
__v: 0
}
Anyone come across this before or know where I am going wrong?
Well I am stupid. The source object was gotten from another mongoose query at the top of the file, this one was an instance of mongoose.Document and therefore couldn't be changed. I added lean() to it to make it return a javascript object and it's all working now.

Categories