Shawn Matthews
Shawn Matthews

Reputation: 1832

Adding values of redux-form field array

For each new item in a FieldArray I'm looking to add together the contents of a Field inside of the FieldArray called total.

So something like this data structure wise in the form state.

test.0.total + test.1.total + test.2.total = testTotal

I'm not sure what my options are for accessing the data in the form. formValueSelector works great if I specifically list out the expected fields, but considering this is a FieldArray I won't know how many items there will be at any given time. How would I loop the array structure to add these fields?

I'm currently using a selector that looks like this to return the array.

const selector = formValueSelector('mainForm');
      export const mapState = (state, ownProps) => {
        const Total = selector(state, 'test');
        return { Total };
      }

How could I potentially build a looping mechanism within the selector?

Something like this works..., but isn't dynamic.

    const selector = formValueSelector('mainForm');
      export const mapState = (state, ownProps) => {
        const test1 = selector(state, 'test.0.total');
        const test2 = selector(state, 'test.1.total');
        const test3 = selector(state, 'test.2.total');
       return { test1, test2, test3, 
        total: test1 + test2 + test3 };
      }

Adding something like this....

const test = selector(state, "test");
const sum = test.reduce((total, item) => total + Number(item.total), 0);

or even this in the return

sum: test.reduce((total, item) => total + Number(item.total), 0);

yeilds a TypeError: Cannot read property 'reduce' of undefined... Even though I can see

I can see that the array isn't undefined in the state... Is there a way to fix this?

enter image description here

Upvotes: 0

Views: 587

Answers (1)

Omar
Omar

Reputation: 3411

const sum = arr.reduce((total, item) => total + Number(item.total), 0);

arr.reduce is what you are looking for.

If you data structure does not contain an object with item.total then replace that part with item.

Upvotes: 1

Related Questions