How to acess child object via param - javascript

I have an Vue app with this data:
data: {
personal: {
email: '',
first_name: '',
last_name: '',
password: '',
password_confirmation: '',
phone: '',
work_email: ''
},
company: {
address: '',
annual_revenue: null,
city_id: null,
country: 'BRA',
company: '',
company_city_document: '',
company_document: '',
company_legal_name: '',
position: '',
state_id: null,
vat: null,
website: '',
work_phone: '',
zipcode: ''
}
}
I want to acess the child object from my mixin, but when i send the propertie via param i get undefined on mixin, im sending like this:
<TextField
#input="checkFormInvalidity('personal.first_name')"
id="first_name"
label="Nome"
/>
When user types anything vue will emit what he typed, in my mixin is a simple verifying method like this:
checkFormInvalidity (field) {
field
? this.$v.data[field].$touch()
: this.$v.$touch()
return field
? !!this.$v.data[field].$invalid
: !!this.$v.$invalid
}
When i do:
console.log(this.data[field])
I receive "undefined" because i don't know how to access the child object from data in that case would be "data.personal.first_name".
If i receive in param "field" only "personal" i can see all data properties.

Related

I am migrating from apollo-link-state to #apollo/client, how do I write default data to InMemoryCache of #apollo/client without using cache.writeData?

I use react 16.13 and am currently migrating from apollo-client 2.x to #apollo/client 3.1.1. I removed a lot of dependency libraries from my packages.json because most of them are now directly importable from #apollo/client. Everything was going fine until I tossed a big rock named "removal of defaults" while migrating from apollo-link-state.
With #apollo/client 3.x, we import InMemoryCache from #apollo/client directly, which is fine. But the withClientState link is no longer existent and ApolloClient doesn't support default values for local cache. I could not find any guide covering this problem. There is one guide for Angular, but it advises to use cache.writeData to construct the cache. Only problem is, in v3.x of #apollo/client, InMemoryCache doesn't have a writeData method anymore. There is a modify method but it is also not straightforward to use, at least I was not able to make it work for this purpose.
I have a large "defaults" object:
export default {
authentication: {
__typename: 'authentication',
auth: ''
},
UserInfo: {
__typename: 'UserInfo',
employee: {
__typename: 'UserInfoEmployee',
defaultShopId: '',
id: '',
email: '',
image: {
__typename: 'image',
id: '',
url: ''
},
firstName: '',
lastName: '',
manager: '',
boss: ''
},
countryCode: '',
chainId: ''
},
defaultShop: {
__typename: 'defaultShop',
id: '',
name: '',
timeZone: null
},
locale: {
__typename: 'locale',
locale: getBrowserLocale()
},
countries: {
__typename: 'countries',
data: []
},
Products: {
__typename: 'Products',
guid: 0,
ProductTypes: {
__typename: 'ProductTypes',
TypeNumber: 0,
type: ''
},
legacyConfiguration: false,
version: '1.0.0'
},
location: {
__typename: 'location',
pathname: '',
search: '',
hash: null,
action: '',
key: null,
isQueryActive: false,
query: null
}
}
How should I write these default data into InMemoryCache without using cache.writeData?
Use writeQuery instead.
I believe in v3 they moved towards using a common way for setting a default state.
Official docs
const query = gql`
query {
authentication #client {
id
__typename
}
...
}`
cache.writeQuery({
query,
data: {
authentication: {
__typename: 'authentication'
...
}
})
it needs to be written using policies, cache.writeQuery didn't work for me at the time of initialization,
cache.policies.addTypePolicies({
Query: {
fields: {
selectedCurrency: {
read() {
return "USD";
},
},
selectedIndex: {
read() {
return 0;
},
},
bookingFlowStep: {
read() {
return '';
},
},
},
},
});

Modyfing already avalable json file with faker

I have a json file which stores the data from mongodb in a array format i want to change some fields in it example email, phone number etc.How can i do it using nodejs and faker?
Exaple of one data.json file
{
_id: 54522,
roles: [ [Object] ],
__v: 48,
name: { last: 'Coke', first: 'Colay' },
cv: {
_id: 54522,
updatedAt: Z,
createdAt: 2Z,
educationEntries: [Array],
workEntries: [Array]
},
unverifiedEmail: null,
unverifiedPhoneNumber: null,
phoneNumberVerificationCode: null,
phoneNumber: '8754552512',
password: 'expected',
emailVerificationCode: 'null',
smoochUserId: '2b390',
},
I want to change phonenumber emailverification and unverfiedEmail entries.
Thanks in advance.

MongoDB updating an object

Currently working on a NodeJS backend with mongoDB. I'm trying to update an Object in mongoDB using NodeJS driver:
"mongodb": "^3.0.2",
I am using the findOneAndUpdate query and have tried the following syntax:
First syntax:
updatedPlayerData = await db.db(MDBC.db).collection(MDBC.pC).findOneAndUpdate({
'username': req.body.username
}, {
$set: {
[profession.city]: '',
[profession.organisation]: '',
[profession.profession]: ''
}
}, { returnOriginal: false });
Second syntax:
updatedPlayerData = await db.db(MDBC.db).collection(MDBC.pC).findOneAndUpdate({
'username': req.body.username
}, {
$set: {
profession: {
city: '',
organisation: '',
profession: ''
}
}
}, { returnOriginal: false });
Also have tried a bunch of other stuff. Can't seem to update the object properly. How can I properly update an object?
You can try this :
db.db(MDBC.db).collection(MDBC.pC).findOneAndUpdate({
'username': req.body.username
}, {
$set: {
'profession.city': '',
'profession.organisation': '',
'profession.profession': ''
}
}, { returnOriginal: false });

ReactJS How to change value of object stored in state

All code will be below my question and explanation.
So what I am trying to do is update my state which is in a grandparent class, this is done for reasons to do with files, I am also using Material-UI for the text boxes.
And I'm also writing Redux without Redux, Because I can just if you see some strange things.
My grandparent class state looks like this:
state = {
value: 0,
application: {
ApplicationPK: '',
Person: [
{
PersonPK: '',
FullName: '',
TitleFK: '',
Forename: '',
MiddleNames: '',
Surname: '',
DateOfBirth: '',
HomeTelephone: '',
MobileTelephone: '',
EmailAddress: '',
LoanPurposeFK: '',
MaritalStatusFK: '',
Addresses: [
{
FlatNumber: '',
BuildingName: '',
BuildingNumber: '',
Street: '',
District: '',
Town: '',
County: '',
Postcode: '',
ResidentialStatusFK: '',
DateMovedIn: '',
IsCurrentAddress: '',
AddressPK: '',
},
],
Employment: [
{
EmploymentStatusFK: '',
Employer: '',
JobTitle: '',
Telephone: '',
MonthlyPay: '',
IsPaidByBACS: '',
PayFrequencyFK: '',
DayOfMonth: '',
DayOfWeek: '',
NextPayDate: '',
FollowingPayDate: '',
DateStarted: '',
Postcode: '',
EmploymentPK: '',
Website: '',
},
],
BankAccount: [
{
Name: '',
Sortcode: '',
AccountNumber: '',
IsAccountHolder: '',
IsJointHolder: '',
IsSoleAuthoriseDebits: '',
IsPrimary: '',
IsActive: '',
BankAccountPK: '',
},
],
},
],
},
};
I know its long but thats because it errors because mui text boxes dont like null values on load.
this is how im changing the state at the moment but its adding it as a value at the top level of the state and i want it to obviously replace the value that is inside person. this function is in the same class as the state obviously
handleChangeType = event => {
this.setState({ [event.target.name]: event.target.value });
}
and Finally the Mui Text Box looks like this:
<Input
defaultValue={this.props.state.application.Person[0].Forename}
className={classes.input}
onChange={this.props.handleChangeType}
name="Forename"
inputProps={{
'aria-label': 'Description',
}}
/>
TL:DR: How do i update the correct value in the state
I know its long but thats because it errors because mui text boxes dont like null values on load.
To avoid initializing a bunch of empty strings everywhere, you could just do:
defaultValue={((this.props.state.application || {}).Person[0] || {}).Forename || ""}
As per updating the correct state variable, I would use a different handler for each category. You must also bear in mind that your state variable here is the Person array. If you want to update anything within it, you need to pass a new array to the state. Finally, you seem to want to be able to have multiple users inside your Persons array, but your event handlers aren't given any info of which user you want to update field X or Y.
For example:
handleChangeType = (userIndex, name, event) => {
let person = Object.assign({}, this.state.Persons[userIndex]); //shallow-copy
person[name] = event.target.value
this.setState({Person: person });
}
For each object or array that's nestled, you'll need to create a copy, change the copy and then replace the original with the copy.

JSON.stringify is not storing object property values

I have the following object in my code:
/* ======= Model ======= */
model = {
workout: [
{
name: '',
email: '',
workouttype: '',
workoutplan: '',
excardio: '',
exstrength: '',
excore: '',
exhiit: '',
validworkout: false,
hasexercises: false
}
]
};
When I try to save the object to localstorage, all the properties are empty.
Here is how I'm storing my object:
saveWorkout: function () {
var key = "Workout",
item = JSON.stringify(model.workout);
localStorage.setItem(key, item);
}
Thanks!

Categories