I'm attempting to get my redux reducer to perform something like this:
.
however, I am outputting the following:
The following is the code I am using to attempt this. I've attempted to include action.userHoldings in the coinData array, however, that also ends up on a different line instead of within the same object. My objective is to get userHoldings within the 0th element of coinData similar to how userHoldings is in the portfolio array in the first image.
import * as actions from '../actions/fetch-portfolio';
const initialState = {
coinData: [],
userHoldings: ''
};
export default function portfolioReducer(state = initialState, action) {
if (action.type === actions.ADD_COIN_TO_PORTFOLIO) {
return Object.assign({}, state, {
coinData: [...state.coinData, action.cryptoData],
userHoldings: action.userHoldings
});
}
return state;
}
I guess you want to do something like this.
return Object.assign({}, state, {
coinData: [ {...state.coinData[0],cryptoData: action.cryptoDatauserHoldings: action.userHoldings}, ...state.coinData.slice(1) ],
});
}
slice(1) is to get all elements except 0th. For the first element, you can construct object the way you like. This should do the trick. Slice returns a new array unlike splice/push or others so safe to use in reducers. :)
Related
Lets start with explaining the structure. I have the page dedicated to a specific company and a component Classification.vue on this page which displays categories of labels and labels itself which are assigned to the current company. First of all I get all possible categories with axios get request, then I get all labels, which are assigned to the current company, and after all I map labels to respective categories. Here is the Classification.vue:
import DoughnutChart from "#comp/Charts/DoughnutChart";
import ModalDialog from '#comp/ModalDialog/ModalDialog';
const EditForm = () => import('./EditForm');
export default {
components: {
DoughnutChart, ModalDialog, EditForm
},
props: ['companyData'],
async created() {
const companyLabels = await this.$axios.get('/companies/' + this.companyData.id + '/labels');
const allLabelsCategories = await this.$axios.get('/labels/categories');
allLabelsCategories.data.map(cat => {
this.$set(this.labelsCategories, cat.labelCategoryId, {...cat});
this.$set(this.labelsCategories[cat.labelCategoryId], 'chosenLabels', []);
});
companyLabels.data.map(l => {
this.labelsCategories[l.label.labelCategory.labelCategoryId].chosenLabels.push({...l.label, percentage: l.percentage})
});
},
computed: {
portfolioChartData() {
let portfolios = [];
// 35 id stands for 'Portfolio' labels category
if (this.labelsCategories[35] !== undefined && this.labelsCategories[35].chosenLabels !== undefined) {
this.labelsCategories[35].chosenLabels.map(label => {
portfolios.push({label: label.name, value: label.percentage});
});
}
return portfolios;
},
portfolioLabels() {
let portfolios = [];
// 35 id stands for Portfolio labels category
if (this.labelsCategories[35] !== undefined && this.labelsCategories[35].chosenLabels !== undefined) {
return this.labelsCategories[35].chosenLabels;
}
return portfolios;
}
},
data() {
return {
labelsCategories: {}
}
}
}
So far so good, I get the object labelsCategories where keys are ids of categories and values are categories objects which now also have chosenLabels key, which we set up in created(). And as you can see I use computed properties, they are necessary for a chart of 'Portfolio' category. And I used $set method in created() exactly for the purpose of triggering reactivity of labelsCategories object so computed properties can respectively react to this.
Now I have a new component inside Classification.vue - EditForm.vue, which is dynamically imported. In this component I do pretty much the same thing, but now I need to get every possible label for every category, not just assigned. So I pass there prop like this:
<modal-dialog :is-visible="isFormActive" #hideModal="isFormActive = false">
<EditForm v-if="isFormActive" ref="editForm" :labels-categories-prop="{...labelsCategories}" />
</modal-dialog>
And EditForm component looks like this:
export default {
name: "EditForm",
props: {
labelsCategoriesProp: {
type: Object,
required: true,
default: () => ({})
}
},
created() {
this.labelsCategories = Object.assign({}, this.labelsCategoriesProp);
},
async mounted() {
let labels = await this.$axios.get('/labels/list');
labels.data.map(label => {
if (this.labelsCategories[label.labelCategoryId].labels === undefined) {
this.$set(this.labelsCategories[label.labelCategoryId], 'labels', []);
}
this.labelsCategories[label.labelCategoryId].labels.push({...label});
});
},
data() {
return {
labelsCategories: {}
}
}
}
And now the problem. Whenever I open modal window with the EditFrom component my computed properties from Calssification.vue are triggered and chart is animating and changing the data. Why? Quite a good question, after digging a bit I noticed, that in EditForm component I also use $set, and if I will add with $set some dummy value, for example:
this.$set(this.labelsCategories[label.labelCategoryId], 'chosenLabels', ['dummy']);
it will overwrite the labelsCategories value in the parent component (Classification.vue)
How is it even possible? As you can see I tried to pass prop as {...labelsCategories} and even did this.labelsCategorie = Object.assign({}, this.labelsCategoriesProp); but my parent object is still affected by changes in child. I compared prop and labelsCategories objects in the EditForm component by === and by 'Object.is()' and they are not the same, so I am completely confused. Any help is highly appreciated.
Btw, I can solve this issue by passing prop as :labels-categories-prop="JSON.parse(JSON.stringify(labelsCategories))" but it seems like a hack to me.
Okay, I was digging deeper in this issue and learned, that neither {...labelsCategories} nor Object.assign({}, this.labelsCategoriesProp) don't create a deep copy of an object only the shallow one. So, I suppose that was the cause of the problem. In this article I learned about shallow and deep copies of objects: https://medium.com/javascript-in-plain-english/how-to-deep-copy-objects-and-arrays-in-javascript-7c911359b089
So, I can leave my hacky way using JSON.parse(JSON.stringify(labelsCategories)) or I can use a library such as lodash:
_.cloneDeep(labelsCategories)
But according to the article I also can create a custom method. And this one option is quite suitable for me. I already had a vue mixin for processing objects, so I just added deepCopy() function there:
deepCopy(obj) {
let outObject, value, key;
if (typeof obj !== "object" || obj === null) {
return obj; // Return the value if obj is not an object
}
// Create an array or object to hold the values
outObject = Array.isArray(obj) ? [] : {};
for (key in obj) {
value = obj[key];
// Recursively (deep) copy for nested objects, including arrays
outObject[key] = this.deepCopy(value);
}
return outObject;
},
I'm trying to update a piece of state with an array of data that I'm getting from the server. This is my reducer:
const schoolsDataReducer = (state = { data: [] }, action) =>
produce(state, draft => {
switch (action.type) {
case SET_INITIAL__DATA:
draft.data = [...action.payload.data]
break
}
})
I get this error:
"Immer does not support setting non-numeric properties on arrays: data"
How am I supposed to store an array of objects?
Are arrays in the state considered bad practice?
Am I missing something?
This happens when you pass something not an object for state. Make sure state is an object.
I have associative array.
It's a key(number) and value(object).
I need to keep state of this array same as it is I just need to update one object property.
Example of array:
5678: {OrderId: 1, Title: "Example 1", Users: [{UserId: 1}, {UserId: 2}, {UserId: 3}]}
5679: {OrderId: 2, Title: "Example 2", Users: [{UserId: 1}, {UserId: 2}, {UserId: 3}]}
I need to update Users array property.
I tried this but it doesn't work:
ordersAssociativeArray: {
...state.ordersAssociativeArray,
[action.key]: {
...state.ordersAssociativeArray[action.key],
Users: action.updatedUsers
}
}
This is data inside reducer.
What I did wrong how to fix this?
Something that might help.
When I inspect values in chrome I check previous value and value after execution of my code above:
Before:
ordersAssociativeArray:Array(22) > 5678: Order {OrderId: ...}
After:
ordersAssociativeArray: > 5678: {OrderId: ...}
Solution (code in my reducer)
let temp = Object.assign([], state.ordersAssociativeArray);
temp[action.key].Users = action.updatedUsers;
return {
...state,
ordersAssociativeArray: temp
}
So this code is working fine.
But I still don't understand why? So I have solution but would like if someone can explain me why this way is working and first not?
If it could help here how I put objects in this associative array initialy:
ordersAssociativeArray[someID] = someObject // this object is created by 'new Order(par1, par2 etc.)'
What you are doing is correct, as demonstrated by this fiddle. There may be problem somewhere else in your code.
Something that I would recommend for you is to separate your reducer into two functions, ordersReducer and orderReducer. This way you will avoid the excessive use of dots, which may be what caused you to doubt the correctness of your code.
For example, something like:
const ordersReducer = (state, action) => {
const order = state[action.key]
return {
...state,
[action.key]: orderReducer(order, action)
}
}
const orderReducer = (state, action) => {
return {
...state,
Users: action.updatedUsers
}
}
I hope you find your bug!
Update
In your solution you use let temp = Object.assign([], state.ordersAssociativeArray);. This is fine, but I thought you should know that it is sometimes preferable to use a {} even when you are indexing by numbers.
Arrays in javascript aren't great for representing normalized data, because if an id is missing the js array will still have an undefined entry at that index. For example,
const orders = []
array[5000] = 1 // now my array has 4999 undefined entries
If you use an object with integer keys, on the other hand, you get nice tightly packed entries.
const orders = {}
orders[5000] = 1 // { 5000: 1 } no undefined entries
Here is an article about normalizing state shape in redux. Notice how they migrate from using an array in the original example, to an object with keys like users1.
The problem can be that you're using array in the state but in the reducer you're putting as object. Try doing:
ordersAssociativeArray: [ //an array and not an object
...state.ordersAssociativeArray,
[action.key]: {
...state.ordersAssociativeArray[action.key],
Users: action.updatedUsers
}
]
It will put ordersAssociative array in your state and not an object.
The initial state looks like this:
const INITIAL_STATE = {
myArray: []
};
Now in my reducer, I want to append a new object to the existing array.
I came up with something like this but it doesn't work as expected.
case ADD_TO_ARRAY:
return {
...state,
myArray: [...state[ { action.payload.key: action.payload.value} ]]
};
Note: I want to create a new object, in line, using the key and value passed in the action payload.
with ES6 you can have dynamically calculated object keys
just add a variable to be evaluated in square brackets []
case ADD_TO_ARRAY:
return {
...state,
myArray: [...state.myArray, [ { [action.payload.key]: action.payload.value} ]]
};
The first thing I tried was this:
const initialState = {
items: {},
showCart: false,
showCheckout: false,
userID: null
};
export default function reducer(state=Immutable.fromJS(initialState), action) {
case 'REMOVE_FROM_CART':
return state.deleteIn(['items', String(action.id)]);
}
When console logging the deleteIn above, it does actually remove the item from the Map correctly. However, the app doesn't re-render again, because I assume I'm mutating the state(?). (mapStateToProps gets called, but no new state).
So next I tried this:
case 'REMOVE_FROM_CART':
const removed = state.deleteIn(['items', String(action.id)]);
const removeItemState = {
...state,
items: { removed }
}
return state.mergeDeep(removeItemState);
But I'm just adding the deleted item to the items again, creating a duplication.
How can I handle this?
Have you tried removing the item after you've deeply cloned the state?
case 'REMOVE_FROM_CART':
const removeItemState = {
...state
items: {
...state.items
}
};
delete removeItemState.items[String(action.id)];
return removeItemState;
How about reduce?
case 'REMOVE_FROM_CART':
return {
...state,
items: Object.keys(state.items).reduce((acc, curr) => {
if (curr !== action.id) acc[curr] = state.items[curr];
return acc;
}, {})
};
Posting more code (such as my reducers setup) may have helped more, but here's what was going on:
First, this code was the right way to remove the item from the state.
return state.deleteIn(['items', String(action.id)]);
However, because I was using the immutable library and not redux-immutable for my combineReducers, my state was not properly being handled. This was allowing me to do things like state.cart.items (in mapStateToProps) where really I should've been using state.getIn(['cart', 'items']).
Changing that magically made the delete work.
Thanks to #jslatts in the Reactiflux Immutable Slack channel for help with figuring this out!