Search code examples
reactjsredux

useSelector and map function React Redux


i want to iterate through an array but Im not sure if i can do this in the useSelector redux hook because it's not giving me the result that i want. Have any of you ever achieved this? or am i going about it completely wrong?

index.jsx

const test = useSelector(state => state.data.map(e => e.details));

data.js

    data: [
        {
            name: 'long neck',
            details: {
                total: 1,
                height: "3ft",
                weight: "34 lbs",               
            }
        },
        {
            name: 'fun fact',
            details: {
                total: 30,
                height: '1ft',
                weight: '16 lbs',
            }
        },
    ],

Solution

  • I my opinion you should not do that.

    Because you are returning a new array every time the useSelector gets called.

    The right way in my opinion is to return the actual data and then do the filtering outside like this.

    const data = useSelector(state => state.data);
    
    const details = calculateDetails() => {
    
       //do all your filtering, mapping, slicing
       return data.map(e => e.details));
    };
    

    The reason I do it this way is to avoid rendering when nothing has changed.

    You should not return new objects out of a useSelector unless you use the second parameter which is an equality checking funcion.