Change object in array if found by idRedux - multiple stores, why not?Why do Redux examples pass empty object as first Object.assign() argument?Is this the correct way to delete an item using redux?Array list in Redux stateRedux - where to prepare dataState as array of objects vs object keyed by idReact redux - issues adding multiple items to an array in state tree objectHow to re-render components when change in store in Redux?Redirect component is rendered but won't change history objectredux state not changing

How to get CPU-G to run on 18.04

Sea level static test of an upper stage possible?

How to avoid theft of potentially patentable IP when trying to obtain a Ph.D?

To find islands of 1 and 0 in matrix

Why can't my huge trees be chopped down?

Sci-fi change: Too much or Not enough

How to apply the changes to my `.zshrc` file after edit?

What does "see" in "the Holy See" mean?

What is this spacecraft tethered to another spacecraft in LEO (vintage)

Are there any examples of technologies have been lost over time?

Did the IBM PC use the 8088's NMI line?

Is a topological space considered to be a class in set theory?

Am I allowed to use personal conversation as a source?

Old French song lyrics with the word "baiser."

Recommendations or Experiences on Archiving Mailing Data

What is the most efficient way to write 'for' loops in Matlab?

Could the rotation of a black hole cause other planets to rotate?

Does academia have a lazy work culture?

Can a table be formatted so that math mode is in some columns and text is in others by default?

What is the most common end of life issue for a car?

Why did House of Representatives need to condemn Trumps Tweets?

Are the named pipe created by `mknod` and the FIFO created by `mkfifo` equivalent?

Why/when is AC-DC-AC conversion superior to direct AC-AC conversion?

If Trump gets impeached, how long would Pence be president?



Change object in array if found by id


Redux - multiple stores, why not?Why do Redux examples pass empty object as first Object.assign() argument?Is this the correct way to delete an item using redux?Array list in Redux stateRedux - where to prepare dataState as array of objects vs object keyed by idReact redux - issues adding multiple items to an array in state tree objectHow to re-render components when change in store in Redux?Redirect component is rendered but won't change history objectredux state not changing






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















According to Redux design patterns if you want to change object in array, you have to use state.items.map, but is it ok to use array.findIndex and if item not found return old state? Is it bad practices, if yes why?




  1. Redux pattern method. Method returns new state, even if room not found.




    const roomId = action.payload.room.id;
    const roomsList = state.roomsList.map(room =>
    if (room.id === roomId)
    return action.payload.room;
    else
    return room;

    );
    return
    ...state,
    roomsList,
    ;




  2. Second way, that I like more. Method returns new state only if room with given ID is found




    const roomId = action.payload.room.id;
    const idx = state.roomsList.findIndex(room => room.id === roomId);
    if(idx!==-1)
    const roomsList = Array.from(state.roomsList);
    roomsList[idx] = action.payload.room;
    return
    ...state,
    roomsList,
    ;
    else
    return state;











share|improve this question




























    1















    According to Redux design patterns if you want to change object in array, you have to use state.items.map, but is it ok to use array.findIndex and if item not found return old state? Is it bad practices, if yes why?




    1. Redux pattern method. Method returns new state, even if room not found.




      const roomId = action.payload.room.id;
      const roomsList = state.roomsList.map(room =>
      if (room.id === roomId)
      return action.payload.room;
      else
      return room;

      );
      return
      ...state,
      roomsList,
      ;




    2. Second way, that I like more. Method returns new state only if room with given ID is found




      const roomId = action.payload.room.id;
      const idx = state.roomsList.findIndex(room => room.id === roomId);
      if(idx!==-1)
      const roomsList = Array.from(state.roomsList);
      roomsList[idx] = action.payload.room;
      return
      ...state,
      roomsList,
      ;
      else
      return state;











    share|improve this question
























      1












      1








      1








      According to Redux design patterns if you want to change object in array, you have to use state.items.map, but is it ok to use array.findIndex and if item not found return old state? Is it bad practices, if yes why?




      1. Redux pattern method. Method returns new state, even if room not found.




        const roomId = action.payload.room.id;
        const roomsList = state.roomsList.map(room =>
        if (room.id === roomId)
        return action.payload.room;
        else
        return room;

        );
        return
        ...state,
        roomsList,
        ;




      2. Second way, that I like more. Method returns new state only if room with given ID is found




        const roomId = action.payload.room.id;
        const idx = state.roomsList.findIndex(room => room.id === roomId);
        if(idx!==-1)
        const roomsList = Array.from(state.roomsList);
        roomsList[idx] = action.payload.room;
        return
        ...state,
        roomsList,
        ;
        else
        return state;











      share|improve this question














      According to Redux design patterns if you want to change object in array, you have to use state.items.map, but is it ok to use array.findIndex and if item not found return old state? Is it bad practices, if yes why?




      1. Redux pattern method. Method returns new state, even if room not found.




        const roomId = action.payload.room.id;
        const roomsList = state.roomsList.map(room =>
        if (room.id === roomId)
        return action.payload.room;
        else
        return room;

        );
        return
        ...state,
        roomsList,
        ;




      2. Second way, that I like more. Method returns new state only if room with given ID is found




        const roomId = action.payload.room.id;
        const idx = state.roomsList.findIndex(room => room.id === roomId);
        if(idx!==-1)
        const roomsList = Array.from(state.roomsList);
        roomsList[idx] = action.payload.room;
        return
        ...state,
        roomsList,
        ;
        else
        return state;








      reactjs redux react-redux






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 26 at 18:40









      Stanley KrutStanley Krut

      294 bronze badges




      294 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          1














          It's always okay to return the previous state if a reducer did not make any changes.



          That's what the default case typically does in the usual switch within a reducer function, like in the example from the official redux docs.






          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55364172%2fchange-object-in-array-if-found-by-id%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            It's always okay to return the previous state if a reducer did not make any changes.



            That's what the default case typically does in the usual switch within a reducer function, like in the example from the official redux docs.






            share|improve this answer



























              1














              It's always okay to return the previous state if a reducer did not make any changes.



              That's what the default case typically does in the usual switch within a reducer function, like in the example from the official redux docs.






              share|improve this answer

























                1












                1








                1







                It's always okay to return the previous state if a reducer did not make any changes.



                That's what the default case typically does in the usual switch within a reducer function, like in the example from the official redux docs.






                share|improve this answer













                It's always okay to return the previous state if a reducer did not make any changes.



                That's what the default case typically does in the usual switch within a reducer function, like in the example from the official redux docs.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 26 at 19:49









                brian-lives-outdoorsbrian-lives-outdoors

                14.8k1 gold badge16 silver badges40 bronze badges




                14.8k1 gold badge16 silver badges40 bronze badges


















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55364172%2fchange-object-in-array-if-found-by-id%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript