I'm trying to destructure an object using the following code.
const searchdata = {
org,
packageName,
description,
keywords
} = this.state;
but I get the following error.
Uncaught ReferenceError: org is not defined
What am I doing wrong here? could we destruture and object into another named object?
added a sample of the state object
this.state = {
searchKey: '',
onValueChange: false,
org: '',
packageName: '',
description: '',
keywords: '',
};
You can do it by way of elimination using object rest:
const state = {
searchKey: '',
onValueChange: false,
org: '',
packageName: '',
description: '',
keywords: '',
};
const {
searchKey,
onValueChange,
...searchdata
} = state;
console.log(searchdata);
Related
My issue is that I have an initial object with data in the function. The function receives params with values that are into this initial object. I need to update the initial object every time with the data, which comes from params.
The code:
export function saveLocalStorage(params = {}) {
let state = {
firstName: '',
lastName: '',
role: '',
idToken: '',
auth: false,
id: '',
email: '',
phone: '',
organizationId: '',
lastVisit: '',
}
localStorage.setItem('donisi-new', JSON.stringify(state))
}
params have the same names as names in initial object, example:
saveLocalStorage({
firstName,
lastName,
role,
organizationId,
auth: true,
idToken,
lastVisit: moment(new Date()),
})
So, for example, the first time I received the first object with params, for example:
saveLocalStorage({
firstName: 'La La',
lastName: 'Bla Bla'
})
and second time I received object with params:
saveLocalStorage({
role: 'admin',
phone: '+111111111'
})
How to update the initial state and don't delete the values and only update them?
Thanks to everybody.
This is a function I use to merge 2 JavaScript objects:
function mergeObjects(obj, src) {
for (var key in src) {
if (src.hasOwnProperty(key)) obj[key] = src[key];
}
return obj;
}
So if you had these 2 objects:
var obj1 = {name: 'Bob', age: 30};
var obj2 = {name: 'Steve'};
And ran the function:
mergeObjects(obj1, obj2);
It would return:
{name: 'Steve', age: 30}
To achieve this behaviour you can use the ES6's spread operator (...) to merge objects. It will merge the two object. The new fields will be added from both object and existing ones will be updated.
Just replace your
localStorage.setItem('donisi-new', JSON.stringify(state))
with
localStorage.setItem('donisi-new', JSON.stringify({...state, ...params}))
The order of state and params is important here. This orders means state object will be updated with new values which exist in params object.
Part of the problem with updating initial state is you have state defined in the function, so those values can't be updated. One way to address this is to pull state out into its own file and then reference it in your function.
// state.js
export default {
firstName: '',
lastName: '',
role: '',
idToken: '',
auth: false,
id: '',
email: '',
phone: '',
organizationId: '',
lastVisit: '',
};
Then in your function you can reference and update it as necessary. The next time you call saveLocalStorage, the state will have been updated from the previous call.
import * as state from "./state.js";
export function saveLocalStorage(params = {}) {
/* Update state with values from params example
for (const [key, value] of Object.entries(params)) {
state[key] = value;
}
*/
localStorage.setItem('donisi-new', JSON.stringify(state))
}
I leave part of this in a comment because you may have something else in mind for updating state or before merging.
In my reducer I want to target a certain key but I think because it has an index, I can't target it with the methods in my reducer. I'm new so help would be appreciated.
Here is my code.
export const initialState = {
sheets: {
0: {
newTabsState: 'details',
name: "Sheet",
details: {
projectUnit: '',
projectName: '',
projectId: '',
projectCompany: '',
projectDesigner: '',
projectClient: ''
},
factors: {
memberName: '',
memberSpecies: '',
memberWeight: '',
memberLength: ''
},
forces: {
forcesUnit: '',
forcesName: '',
forcesId: '',
forcesCompany: '',
forcesDesigner: '',
forcesClient: ''
}
}
}
}
I want to be able to target newTabState so I can add a value to it but my IDE gives me an error when I try to add an index at the reducer method
The code below doesn't work... can you tell me what to do? I want to learn how.
const setNewtabState = (state, payload) => {
return {
...state,
sheets: {
...state,
newTabsState: payload
}
}
}
You can access newTabState like this initialState.sheets[0].newTabState.
I want to point out that when using an object in JavaScript as you do, there is no such thing as an index. An object only has keys and values and the key can be any arbitrary string or number. So what we access is a key represented by the number 0.
If you need proper indexes, you should use an array (which has the reduce method natively).
references:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
This should work:
return {
sheets: {
0: {
...state.sheets[0],
newTabsState: payload
}
}
On my edit page of CRUD project, I have a code that fills the form with values of which record is being edited. I use v-model to define HTML inputs, but the code seems too long.
I get the data from the prop, and fill the v-model.
My code that fills v-model
created() {
this.studentData = this.student;
this.first_name = this.student.first_name;
this.last_name = this.student.last_name;
this.student_number = this.student.last_name;
this.phone_number = this.student.phone_number;
this.email = this.student.email;
this.birth_date = moment(this.student.birth_date).format('YYYY-MM-DD');
this.school_name = this.student.school_name;
}
The way I get the data using prop: props: ['student'] and in blade <student-edit-component :student="{{$student}}">
Defining v-models in script
data () {
return {
first_name: '',
last_name: '',
student_number: '',
phone_number: '',
email: '',
birth_date: '',
school_name: '',
};
},
That fills the value on the form inputs with it's data.
Is there a way to shorten this code using props or arrays?
Please help me, I'm so new to Vue
You can change your model of data adding a new layer. For example:
data() {
return {
currentStudent: {
first_name: '',
last_name: '',
student_number: '',
phone_number: '',
email: '',
birth_date: '',
school_name: '',
}
}
},
Then in created you can use simple
created() {
this.currentStudent = this.student;
this.currentStudent.birth_date = moment(this.student.birth_date).format('YYYY-MM-DD');
},
And in all component replace names by names with currentStudne eg in v-models:
first_name -> currentStudne.first_name
You can also read about Vue.$set
https://v2.vuejs.org/v2/guide/reactivity.html
You can use the object studentData, it is working well with v-model.
First, you pass the props like that :
<student-edit-component :student="student"> (no need to use the ${{}}).
Then in the component `StudentEditComponent', you can use :
props: {
student: {
type: Object,
required: true,
default : () => {},
}
}
You should use the type, required and default properties, it is a good practice.
Then
data () {
return {
studentForm: {},
};
},
created() {
this.studentForm = this.student;
}
In the template, you can after that use v-model="studentForm.first_name"
I am trying to setup relations between types and wrote a resolver to run a mutation that create the list values but getting the below error
here is my mutation file
async createList(parent, args, ctx, info) {
const list = await ctx.db.mutation.createList(
{
data: {
project: {
connect: {
id: args.projectId
}
},
...args
}
},
info
);
return list;
}
and here is my datamodel
type Board {
id: ID! #id
title: String!
createdAt: DateTime! #createdAt
updatedAt: DateTime! #updatedAt
lists: [List]!
}
type List {
id: ID! #id
title: String!
createdAt: DateTime! #createdAt
updatedAt: DateTime! #updatedAt
project: Board!
}
and my schema is
type Mutation {
createList(title: String!, projectId: ID!): List!
}
and the generated prisma file
type Mutation {
createList(data: ListCreateInput!): List!
}
input ListCreateInput {
id: ID
title: String!
project: BoardCreateOneWithoutListsInput!
}
I expected this mutation to run and create the values but got this error instead
Error: Variable "$_v0_data" got invalid value { project: { connect: [Object] }, title: "to do", projectId: "cjyey7947hh6x0b36m231qhbc" }; Field "projectId" is not defined by type ListCreateInput. Did you mean project?
at new CombinedError (/Users/gabroun/Documents/Sites/react-kanban/server/node_modules/graphql-tools/dist/stitching/errors.js:82:28)
at Object.checkResultAndHandleErrors (/Users/gabroun/Documents/Sites/react-kanban/server/node_modules/graphql-tools/dist/stitching/errors.js:98:15)
at CheckResultAndHandleErrors.transformResult (/Users/gabroun/Documents/Sites/react-kanban/server/node_modules/graphql-tools/dist/transforms/CheckResultAndHandleErrors.js:9:25)
at /Users/gabroun/Documents/Sites/react-kanban/server/node_modules/graphql-tools/dist/transforms/transforms.js:18:54
at Array.reduce (<anonymous>)
at applyResultTransforms (/Users/gabroun/Documents/Sites/react-kanban/server/node_modules/graphql-tools/dist/transforms/transforms.js:17:23)
at /Users/gabroun/Documents/Sites/react-kanban/server/node_modules/graphql-tools/dist/stitching/delegateToSchema.js:97:50
at step (/Users/gabroun/Documents/Sites/react-kanban/server/node_modules/graphql-tools/dist/stitching/delegateToSchema.js:31:23)
at Object.next (/Users/gabroun/Documents/Sites/react-kanban/server/node_modules/graphql-tools/dist/stitching/delegateToSchema.js:12:53)
at fulfilled (/Users/gabroun/Documents/Sites/react-kanban/server/node_modules/graphql-tools/dist/stitching/delegateToSchema.js:3:58)
Consider using the following code
async function createList(parent, { title, projectId }, ctx, info) {
const list = await ctx.db.mutation.createList(
{
data: {
project: {
connect: {
id: projectId,
},
},
title,
},
},
info,
)
return list
}
The reason for getting the error is because ...args is used, so all the attributes in args will be passed to data as follows
data:{
project:{...},
title:'',
projectId:'',
}
ListCreateInput only needs title and project. The extra projectId becomes accidentally causing an error.
From last couple of hours, I'm trying to set simple array but somehow its not happening.
messages : [{message: string, nickname: string, user_id: string, profile_url: string, created_at: string, type: string}];
loadMessages(channelUrl){
this.getChannel(channelUrl)
.then(channel => {
this.channel = channel;
this.getMessageList(this.channel)
.then(messageList => {
this.messageList = messageList;
console.log(this.messageList);
this.messageList.forEach((messageData)=>{
console.log(messageData.message);
this.messages.push({message: messageData.message, nickname: '', user_id: '', profile_url: '', created_at: '', type: ''});
console.log(this.messages);
});
})
.catch(error => {
return error.message;
});
})
}
last console.log is not getting printed. neither its giving any errors.
Please guide.
Champagne has helped me to find the solution. I have added try catch because of that error was not getting displayed.
this.messages
was undefined