I have a state like this:
this.state ={
photos: [
{ description: 'someDescription', id: 1 },
{ description: 'someDescription', id: 2 },
{ description: 'someDescription', id: 3 }
]
}
How can I update one of the descriptions only?
Or I have to do something like
this.setState({ photos: newArrayOfObjectsWithOnlyOneUpdatedDescription })
You can create a funtion to do it for you like this:
const updatePhoto = (id, desc) =>
this.state.photos.map((obj) =>
obj.id === id ? Object.assign(obj, { description: desc }) : obj)
map function will return a new array, so you won't need to do a manual state cloning stuff.
Then reuse it as you need it:
this.setState({ photos: updatePhoto(2, 'new desc') })
You can create copy of state, then update copied state and setState
let stateCopy = Object.assign({}, this.state); // get the current state copy
stateCopy.photos = stateCopy.photos.slice(); // get photos object
stateCopy.photos[key] = Object.assign({}, stateCopy.photos[key]);
stateCopy.photos[key].description = 'new decription'; // update description of specific key
this.setState(stateCopy); // set state
Related
In Vuex i try to send some values to a store, like this.
getStorage(
{ commit },
name: String | undefined = undefined,
objectA: ObjectA | undefined = undefined,
objectB: ObjectB | undefined = undefined
) {
if (selectedItinerary) {
commit('setA', objectA, objectB)
} else if (name) {
commit('setB', name)
}
},
The problem: Only get name value, objectA and objectB return undefinied.
So: Somebody say what's wrong? Maybe can only send one param?
UPDATE 1
Calling dispatch
this.$store.dispatch('business/getLocalStorage', {
name: this.name,
})
Store
getLocalStorage({ commit }, item) {
if (item.name) {
commit('setLocalStorageItinerary', item.name)
}
}
setLocalStorageItinerary(state, { name }: { name: string }) {
if (name) {
const itinerary = new LocalStorage()
itinerary.name = name
state.itinerary = itinerary
}
},
Assuming getStorage is an action, which receive the Vuex context as the first argument and a payload as the second, just wrap your values up inside an object before passing it as the payload.
eg.
somewhere in your app...
let payload = {
name: someValue,
objectA: someObject,
objectB: someOtherObject
}
this.$store.dispatch('getStorage', payload)
actions.js
getStorage({ commit }, payload) {
if (selectedItinerary) {
commit('setA', payload.objectA, payload.objectB)
} else if (payload.name) {
commit('setB', payload.name)
}
}
It isn't clear from your example where selectedItinerary is defined, but I think you get the gist from the above.
in my Nuxt.js app
my store object is:
export const state = () => ({
curEditRP: {
attributes:{
name:"",
spouse: {
type: "", // wife/husband
name: ""
}
}
})
to update the attributes of curEditRP i wrote mutations function that called setCurEditRPAttrState:
export const mutations = {
setCurEditRPAttrState(state, payload) {
state.curEditRP.attributes[payload.attr] = payload.value;
},
}
from template i used it:
this.$store.commit("setCurEditRPAttrState", {
value: value,
attr: attributeName,
});
In a name update it works great
But in a spouse update it throws an error
Error: [vuex] do not mutate vuex store state outside mutation handlers
examples of values:
name (works great):
this.$store.commit("setCurEditRPAttrState", {
value: "Peter",
attr: "name",
});
spouse (throws an error):
this.$store.commit("setCurEditRPAttrState", {
value: { type:"wife",name:"S" },
attr: "spouse",
});
clarification: value is v-model variable
Bs"d, I find the solution.
in update object or array of object i need itarate over object properties and update each one individually
setCurEditRPAttrState(state, payload) {
if(typeof(payload.value) == 'object') {
let stateAttribute = state.curEditRP.attributes[payload.attr];
if(Array.isArray(payload.value)) {
let stateArrLen = stateAttribute.length;
let valuelen = payload.value.length;
while(stateArrLen > valuelen) {
stateAttribute.pop();
stateArrLen --;
}
for (let index = 0; index < payload.value.length; index++) {
const element = payload.value[index];
if(stateAttribute.length < index + 1) stateAttribute.push({});
Object.keys(element).forEach( key => {
Vue.set(stateAttribute[index], key, element[key])
})
}
}
else {
Object.keys(payload.value).forEach( key => {
Vue.set(stateAttribute, key, payload.value[key])
})
}
}
else {
state.curEditRP.attributes[payload.attr] = payload.value;
}
},
I would like to reorder arrays when using mobx state tree.
Say I have this example taken from the example page.
How do I get to reorder my ToDos in the TodoStore.
As a simplified example, say my todos are ['todo1, todo2'], how do I change them so that the new array is ['todo2, todo1']?
const Todo = types
.model({
text: types.string,
completed: false,
id: types.identifierNumber
})
.actions((self) => ({
remove() {
getRoot(self).removeTodo(self)
},
edit(text) {
if (!text.length) self.remove()
else self.text = text
},
toggle() {
self.completed = !self.completed
}
}))
const TodoStore = types
.model({
todos: types.array(Todo),
filter: types.optional(filterType, SHOW_ALL)
})
.views((self) => ({
get completedCount() {
return self.todos.filter((todo) => todo.completed).length
},
}))
.actions((self) => ({
addTodo(text) {
const id = self.todos.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1
self.todos.unshift({ id, text })
},
removeTodo(todo) {
destroy(todo)
},
}))
export default TodoStore
Thanks a lot!
If you want move the second todo to the first index in the array you could create a new action and splice the second todo out and then unshift it back in:
swapFirstTwoTodos() {
const secondTodo = self.todos.splice(1, 1)[0];
self.todos.unshift(secondTodo);
}
I'm struggling to create a query with sequelize.
Some context
I have the following models:
A Manifestation can have [0..n] Event
An Event belongs to one Manifestation (an Event cannot exist without a Manifestation)
A Place can have [0..n] Event
An Event belongs to one Place (an Event cannot exist without a Place)
A Manifestation can have [1..n] Place
A Place can have [0..n] Manifestation
I model the relations as the following:
Manifestation.hasMany(Event, { onDelete: 'CASCADE', hooks: true })
Event.belongsTo(Manifestation)
Place.hasMany(Event, { onDelete: 'CASCADE', hooks: true })
Event.belongsTo(Place)
Manifestation.belongsToMany(Place, { through: 'manifestation_place' })
Place.belongsToMany(Manifestation, { through: 'manifestation_place' })
For me it seems rather correct, but don't hesitate if you have remarks.
The question
I'm trying to query the Place in order to get all Manifestation and Event happening in a given Place. But for the Event ones, I want to include them within their Manifestation even if the Manifestation doesn't happen in the given Place.
Below is the "JSON" structure I'm trying to achieve:
{
id: 1,
name: "Place Name",
address: "Place address",
latitude: 47.00000,
longitude: -1.540000,
manifestations: [
{
id: 10,
title: "Manifestation one",
placeId: 1,
events: []
},
{
id: 11,
title: "Manifestation two",
placeId: 3,
events: [
id: 5,
title: "3333",
manifestationId: 11,
placeId: 1
]
}
]
}
So I want to include the Manifestation with id: 11, because one of its Event occurs in the given Place (with id: 1)
Update (04/06/20): For now I rely on javascript to get the expected result
I figured out it would be nice if I posted my current solution before asking.
router.get('/test', async (req, res) => {
try {
const placesPromise = place.findAll()
const manifestationsPromise = manifestation.findAll({
include: [
{ model: event },
{
model: place,
attributes: ['id'],
},
],
})
const [places, untransformedManifestations] = await Promise.all([
placesPromise,
manifestationsPromise,
])
const manifestations = untransformedManifestations.map(m => {
const values = m.toJSON()
const places = values.places.map(p => p.id)
return { ...values, places }
})
const result = places
.map(p => {
const values = p.toJSON()
const relatedManifestations = manifestations
.filter(m => {
const eventsPlaceId = m.events.map(e => e.placeId)
return (
m.places.includes(values.id) ||
eventsPlaceId.includes(values.id)
)
})
.map(m => {
const filteredEvents = m.events.filter(
e => e.placeId === values.id
)
return { ...m, events: filteredEvents }
})
return { ...values, manifestations: relatedManifestations }
})
.filter(p => p.manifestations.length)
return res.status(200).json(result)
} catch (err) {
console.log(err)
return res.status(500).send()
}
})
But I'm pretty sure I could do that directly with sequelize. Any ideas or recommendations ?
Thanks
This is not optimum. But you can try it out:
const findPlace = (id) => {
return new Promise(resolve => {
db.Place.findOne({
where: {
id: id
}
}).then(place => {
db.Manefestation.findAll({
include: [{
model: db.Event,
where: {
placeId: id
}
}]
}).then(manifestations => {
const out = Object.assign({}, {
id: place.id,
name: place.name,
address: place.address,
latitude: place.latitude,
longitude: place.longitude,
manifestations: manifestations.reduce((res, manifestation) => {
if (manifestation.placeId === place.id || manifestation.Event.length > 0) {
res.push({
id: manifestation.id,
title: manifestation.id,
placeId: manifestation.placeId,
events: manifestation.Event
})
}
return res;
}, [])
})
})
resolve(out);
})
})
}
From this, you get all manifestations that assigned to place or have any event that assigns. All included events in the manefestations are assigned to the place.
Edit :
You will be able to use the following one too:
const findPlace = (id) => {
return new Promise(resolve => {
db.Place.findOne({
include: [{
model: db.Manefestation,
include: [{
model: db.Event,
where: {
placeId: id
}
}]
}],
where: {
id: id
}
}).then(place => {
db.Manefestation.findAll({
include: [{
model: db.Event,
where: {
placeId: id
}
}],
where: {
placeId: {
$not: id
}
}
}).then(manifestations => {
place.Manefestation = place.Manefestation.concat(manifestations.filter(m=>m.Event.length>0))
resolve(place);// or you can rename, reassign keys here
})
})
})
}
Here I take only direct manifestations in the first query. Then, manifestations that not included and concatenate.
I do not know if you figure it out by now. But the solution is provided below.
Search with Sequelize could get funny :). You have to include inside another include. If the query gets slow use separate:true.
Place.findAll({
include: [
{
model: Manifestation,
attributes: ['id'],
include: [{
model: Event ,
attributes: ['id']
}]
},
],
})
I tried to complete it in a single query but you will still need JavaScript to be able to get the type of output that you want.
(Note: 💡 You need manifestation which is not connected to places but should be included if a event is present of that place. The only SQL way to get that starts by doing a CROSS JOIN between all tables and then filtering out the results which will be a very hefty query)
I came up with this code(tried & executed) which doesn't need you to execute 2 findAll that fetches all data as what you are currently using. Instead it fetched only the data needed for final output in 1 query.
const places = await Place.findAll({
include: [{
model: Manifestation,
// attributes: ['id']
through: {
attributes: [], // this helps not get keys/data of join table
},
}, {
model: Event,
include: [{
model: Manifestation,
// attributes: ['id']
}],
}
],
});
console.log('original output places:', JSON.stringify(places, null, 2));
const result = places.map(p => {
// destructuring to separate out place, manifestation, event object keys
const {
manifestations,
events,
...placeData
} = p.toJSON();
// building modified manifestation with events array
const _manifestations = manifestations.map(m => {
return ({ ...m, events: [] })
});
// going through places->events to push them to respective manifestation events array
// + add manifestation which is not directly associated to place but event is of that manifestation
events.map(e => {
const {
manifestation: e_manifestation, // renaming variable
...eventData
} = e;
const mIndex = _manifestations.findIndex(m1 => m1.id === e.manifestationId)
if (mIndex === -1) { // if manifestation not found add it with the events array
_manifestations.push({ ...e_manifestation, events: [eventData] });
} else { // if found push it into events array
_manifestations[mIndex].events.push(eventData);
}
});
// returning a place object with manifestations array that contains events array
return ({ ...placeData, manifestations: _manifestations });
})
// filter `.filter(p => p.manifestations.length)` as used in your question
console.log('modified places', JSON.stringify(result, null, 2));
i want to create a object with multiple object. the data is something like this
dataList = [{inputFieldId: 1, dataField:{...}, data: '120'}, {inputFieldId: 2, dataField:{...}, data: '120'} ]
what is want like this.
res = [{1: '120'}, {2: '120'}]
i write a code for this but its giving me the last object data only.
constructor(){
super()
this.state = {
inputValue:{},
datalist = [],
}
}
componentDidMount() {
console.log(this.state.inputValue)
this.props.navigation.setParams({ sendDataToServer:
this._sendDataToServer });
}
async componentWillMount(){
for(var key in dataList){
this.setState({
inputValue: {
...this.state.inputValue,
[dataList[key].inputFieldId]: dataList[key].data
}
})
}
}
code output = { 2: '120'}
thanks in advance
setState work asynchronously. Instead of this
this.setState({
inputValue: {
...this.state.inputValue,
[dataList[key].inputFieldId]: dataList[key].data
}
})
Try to change to this
this.setState((previousState) => ({
inputValue: {
...previousState.inputValue,
[dataList[key].inputFieldId]: dataList[key].data
}
}))