0

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

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

7 Comments

Any thoughts on how this would integrate with redux-form?
Added the use case. I tried to keep it minimal to prevent TLDR.
you need to grab your array from state and reduce it just like I did in my example and return the value.
So this looks like it would work, but returns a TypeError: Cannot read property 'reduce' of undefined. Is there something I'm missing on this?
is the data structure your passing an array and is it empty? Add this logic before you reduce arr && arr.reduce'rest of code....'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.