List Updates IncorrectlyUse ReactJS in ASP.Net Core without React.ASPNet libraryDoes React batch state update functions when using hooks?react hook's setState does not appear to be updating the valueuseState is accepting updates if the object reference does not changeUncaught TypeError: Cannot read property 'current' of undefined react-dom.production.min.js:134 at VgReact Hooks: updating multiple hook states atomicallystate is not being updated when using React HooksReact hooks useEffect only on update?React hooks state isnt updatedHow to update state inside conditional logic?

The teacher logged me in as administrator for doing a short task, is the whole system now compromised?

Why aren't RCS openings an issue for spacecraft heat shields?

In what ways can a Non-paladin access Paladin spells?

Why did this happen to Thanos's ships at the end of "Avengers: Endgame"?

Are illustrations in novels frowned upon?

In an emergency, how do I find and share my position?

Vacuum collapse -- why do strong metals implode but glass doesn't?

How much code would a codegolf golf if a codegolf could golf code?

How to refer to a regex group in awk regex?

Can you feel passing through the sound barrier in an F-16?

Why we don't have vaccination against all diseases which are caused by microbes?

When translating the law, who ensures that the wording does not change the meaning of the law?

Why is 日本 read as "nihon" but not "nitsuhon"?

Is it best to use a tie when using 8th notes off the beat?

Efficiently pathfinding many flocking enemies around obstacles

Fancy String Replace

Is it appropriate for a prospective landlord to ask me for my credit report?

Does an object count as "being moved" when placed in a Bag of Holding before its wielder moves, and then after moving they take the object out again?

Is there a known non-euclidean geometry where two concentric circles of different radii can intersect? (as in the novel "The Universe Between")

Which household object drew this pattern?

Why didn’t Doctor Strange stay in the original winning timeline?

What is the hex versus octal timeline?

Can pay be witheld for hours cleaning up after closing time?

Is “I am getting married with my sister” ambiguous?



List Updates Incorrectly


Use ReactJS in ASP.Net Core without React.ASPNet libraryDoes React batch state update functions when using hooks?react hook's setState does not appear to be updating the valueuseState is accepting updates if the object reference does not changeUncaught TypeError: Cannot read property 'current' of undefined react-dom.production.min.js:134 at VgReact Hooks: updating multiple hook states atomicallystate is not being updated when using React HooksReact hooks useEffect only on update?React hooks state isnt updatedHow to update state inside conditional logic?






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








1















A very simple list with inputs that are supposed to be addable and updatable.
The problem occurs after I add one or more inputs and then try to type inside of one of the inputs - all inputs after the one being typed in disappear.



It has something to do with memo-ing the Item component and I'm looking to understand what exactly is happening there (valueChanged getting cached?). I can't wrap my head around.



Without the memo function the code works as expected but of course, all inputs get updated on every change.



Here's a gif of what's happening: https://streamable.com/gsgvi



To replicate paste the code below into an HTML file or take a look here: https://codesandbox.io/s/81y3wnl142



<style>
ul
list-style-type:none;
padding:0;


input[type=text]
margin:0 10px;

</style>


<div id="app"></div>

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script crossorigin src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
<script type="text/babel">

const randomStr = () => Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 10);
const useState, memo, Fragment = React



const Item = memo(( value, i, valueChanged ) =>

console.log('item rendering...');

return <li>
<input type='text' value=value onChange=e => valueChanged(i, e.target.value)/>
</li>
, (o, n) => o.value === n.value)


const ItemList = ( items, valueChanged ) =>

return <ul>
items.map(( key, title , i) => (
<Item
key=key
i=i
value=title
valueChanged=valueChanged
/>
))
</ul>




const App = () =>

const [items, setItems] = useState([
key: randomStr(), title: 'abc' ,
key: randomStr(), title: 'def' ,
])

const valueChanged = (i, newVal) =>
let updatedItems = [...items]
updatedItems[i].title = newVal
setItems(updatedItems)


const addNew = () =>
let newItems = [...items]
newItems.push( key: randomStr(), title:'' )
setItems(newItems)


return <Fragment>
<ItemList items=items valueChanged=valueChanged/>
<button onClick=addNew>Add new</button>
</Fragment>



ReactDOM.render(<App/>, document.querySelector('#app'))


</script>










share|improve this question


























  • I removed (o, n) => o.value === n.value) i.e second parameter from the memo and it is working fine.

    – Utsav Patel
    Mar 27 at 16:16











  • I tried both my fix and @UjinT34's fix behavior seems to resolve with either one. I upvoted your question and the other answer by Ujin. Good job with a well-structured question and examples, also including your potential fixes.

    – Jacob
    Mar 27 at 16:26

















1















A very simple list with inputs that are supposed to be addable and updatable.
The problem occurs after I add one or more inputs and then try to type inside of one of the inputs - all inputs after the one being typed in disappear.



It has something to do with memo-ing the Item component and I'm looking to understand what exactly is happening there (valueChanged getting cached?). I can't wrap my head around.



Without the memo function the code works as expected but of course, all inputs get updated on every change.



Here's a gif of what's happening: https://streamable.com/gsgvi



To replicate paste the code below into an HTML file or take a look here: https://codesandbox.io/s/81y3wnl142



<style>
ul
list-style-type:none;
padding:0;


input[type=text]
margin:0 10px;

</style>


<div id="app"></div>

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script crossorigin src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
<script type="text/babel">

const randomStr = () => Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 10);
const useState, memo, Fragment = React



const Item = memo(( value, i, valueChanged ) =>

console.log('item rendering...');

return <li>
<input type='text' value=value onChange=e => valueChanged(i, e.target.value)/>
</li>
, (o, n) => o.value === n.value)


const ItemList = ( items, valueChanged ) =>

return <ul>
items.map(( key, title , i) => (
<Item
key=key
i=i
value=title
valueChanged=valueChanged
/>
))
</ul>




const App = () =>

const [items, setItems] = useState([
key: randomStr(), title: 'abc' ,
key: randomStr(), title: 'def' ,
])

const valueChanged = (i, newVal) =>
let updatedItems = [...items]
updatedItems[i].title = newVal
setItems(updatedItems)


const addNew = () =>
let newItems = [...items]
newItems.push( key: randomStr(), title:'' )
setItems(newItems)


return <Fragment>
<ItemList items=items valueChanged=valueChanged/>
<button onClick=addNew>Add new</button>
</Fragment>



ReactDOM.render(<App/>, document.querySelector('#app'))


</script>










share|improve this question


























  • I removed (o, n) => o.value === n.value) i.e second parameter from the memo and it is working fine.

    – Utsav Patel
    Mar 27 at 16:16











  • I tried both my fix and @UjinT34's fix behavior seems to resolve with either one. I upvoted your question and the other answer by Ujin. Good job with a well-structured question and examples, also including your potential fixes.

    – Jacob
    Mar 27 at 16:26













1












1








1


1






A very simple list with inputs that are supposed to be addable and updatable.
The problem occurs after I add one or more inputs and then try to type inside of one of the inputs - all inputs after the one being typed in disappear.



It has something to do with memo-ing the Item component and I'm looking to understand what exactly is happening there (valueChanged getting cached?). I can't wrap my head around.



Without the memo function the code works as expected but of course, all inputs get updated on every change.



Here's a gif of what's happening: https://streamable.com/gsgvi



To replicate paste the code below into an HTML file or take a look here: https://codesandbox.io/s/81y3wnl142



<style>
ul
list-style-type:none;
padding:0;


input[type=text]
margin:0 10px;

</style>


<div id="app"></div>

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script crossorigin src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
<script type="text/babel">

const randomStr = () => Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 10);
const useState, memo, Fragment = React



const Item = memo(( value, i, valueChanged ) =>

console.log('item rendering...');

return <li>
<input type='text' value=value onChange=e => valueChanged(i, e.target.value)/>
</li>
, (o, n) => o.value === n.value)


const ItemList = ( items, valueChanged ) =>

return <ul>
items.map(( key, title , i) => (
<Item
key=key
i=i
value=title
valueChanged=valueChanged
/>
))
</ul>




const App = () =>

const [items, setItems] = useState([
key: randomStr(), title: 'abc' ,
key: randomStr(), title: 'def' ,
])

const valueChanged = (i, newVal) =>
let updatedItems = [...items]
updatedItems[i].title = newVal
setItems(updatedItems)


const addNew = () =>
let newItems = [...items]
newItems.push( key: randomStr(), title:'' )
setItems(newItems)


return <Fragment>
<ItemList items=items valueChanged=valueChanged/>
<button onClick=addNew>Add new</button>
</Fragment>



ReactDOM.render(<App/>, document.querySelector('#app'))


</script>










share|improve this question
















A very simple list with inputs that are supposed to be addable and updatable.
The problem occurs after I add one or more inputs and then try to type inside of one of the inputs - all inputs after the one being typed in disappear.



It has something to do with memo-ing the Item component and I'm looking to understand what exactly is happening there (valueChanged getting cached?). I can't wrap my head around.



Without the memo function the code works as expected but of course, all inputs get updated on every change.



Here's a gif of what's happening: https://streamable.com/gsgvi



To replicate paste the code below into an HTML file or take a look here: https://codesandbox.io/s/81y3wnl142



<style>
ul
list-style-type:none;
padding:0;


input[type=text]
margin:0 10px;

</style>


<div id="app"></div>

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script crossorigin src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
<script type="text/babel">

const randomStr = () => Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 10);
const useState, memo, Fragment = React



const Item = memo(( value, i, valueChanged ) =>

console.log('item rendering...');

return <li>
<input type='text' value=value onChange=e => valueChanged(i, e.target.value)/>
</li>
, (o, n) => o.value === n.value)


const ItemList = ( items, valueChanged ) =>

return <ul>
items.map(( key, title , i) => (
<Item
key=key
i=i
value=title
valueChanged=valueChanged
/>
))
</ul>




const App = () =>

const [items, setItems] = useState([
key: randomStr(), title: 'abc' ,
key: randomStr(), title: 'def' ,
])

const valueChanged = (i, newVal) =>
let updatedItems = [...items]
updatedItems[i].title = newVal
setItems(updatedItems)


const addNew = () =>
let newItems = [...items]
newItems.push( key: randomStr(), title:'' )
setItems(newItems)


return <Fragment>
<ItemList items=items valueChanged=valueChanged/>
<button onClick=addNew>Add new</button>
</Fragment>



ReactDOM.render(<App/>, document.querySelector('#app'))


</script>







reactjs react-hooks






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 16:40









Jacob

3842 silver badges13 bronze badges




3842 silver badges13 bronze badges










asked Mar 27 at 16:02









IvannnnnIvannnnn

301 silver badge6 bronze badges




301 silver badge6 bronze badges















  • I removed (o, n) => o.value === n.value) i.e second parameter from the memo and it is working fine.

    – Utsav Patel
    Mar 27 at 16:16











  • I tried both my fix and @UjinT34's fix behavior seems to resolve with either one. I upvoted your question and the other answer by Ujin. Good job with a well-structured question and examples, also including your potential fixes.

    – Jacob
    Mar 27 at 16:26

















  • I removed (o, n) => o.value === n.value) i.e second parameter from the memo and it is working fine.

    – Utsav Patel
    Mar 27 at 16:16











  • I tried both my fix and @UjinT34's fix behavior seems to resolve with either one. I upvoted your question and the other answer by Ujin. Good job with a well-structured question and examples, also including your potential fixes.

    – Jacob
    Mar 27 at 16:26
















I removed (o, n) => o.value === n.value) i.e second parameter from the memo and it is working fine.

– Utsav Patel
Mar 27 at 16:16





I removed (o, n) => o.value === n.value) i.e second parameter from the memo and it is working fine.

– Utsav Patel
Mar 27 at 16:16













I tried both my fix and @UjinT34's fix behavior seems to resolve with either one. I upvoted your question and the other answer by Ujin. Good job with a well-structured question and examples, also including your potential fixes.

– Jacob
Mar 27 at 16:26





I tried both my fix and @UjinT34's fix behavior seems to resolve with either one. I upvoted your question and the other answer by Ujin. Good job with a well-structured question and examples, also including your potential fixes.

– Jacob
Mar 27 at 16:26












2 Answers
2






active

oldest

votes


















4













valueChanged is a closure which gets a fresh items every render. But your memo doesn't trigger an update because it only checks (o, n) => o.value === n.value. The event handler inside Item uses the old items value.



It can be fixed with functional updates:



const valueChanged = (i, newVal) => 
setItems(oldItems =>
let updatedItems = [...oldItems];
updatedItems[i].title = newVal;
return updatedItems;
);



So valueChanged doesn't depend on items and doesn't need to be checked by memo.



Your code might have similar problems with other handlers. It is better to use functional updates whenener new value is based on the old one.






share|improve this answer




















  • 1





    Ah, ok. That's kind of what I thought... Thanks a lot.

    – Ivannnnn
    Mar 27 at 16:23











  • I am liking this answer as well. Seems to solve the issue another way.

    – Jacob
    Mar 27 at 16:23


















0













You can try initializing the state this way, I tried it on codesandbox and it may be the behavior you are looking for.



https://codesandbox.io/s/q8l6m2lj64



 const [items, setItems] = useState(() => [
key: randomStr(), title: 'abc' ,
key: randomStr(), title: 'def' ,
]);





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%2f55381648%2flist-updates-incorrectly%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    4













    valueChanged is a closure which gets a fresh items every render. But your memo doesn't trigger an update because it only checks (o, n) => o.value === n.value. The event handler inside Item uses the old items value.



    It can be fixed with functional updates:



    const valueChanged = (i, newVal) => 
    setItems(oldItems =>
    let updatedItems = [...oldItems];
    updatedItems[i].title = newVal;
    return updatedItems;
    );



    So valueChanged doesn't depend on items and doesn't need to be checked by memo.



    Your code might have similar problems with other handlers. It is better to use functional updates whenener new value is based on the old one.






    share|improve this answer




















    • 1





      Ah, ok. That's kind of what I thought... Thanks a lot.

      – Ivannnnn
      Mar 27 at 16:23











    • I am liking this answer as well. Seems to solve the issue another way.

      – Jacob
      Mar 27 at 16:23















    4













    valueChanged is a closure which gets a fresh items every render. But your memo doesn't trigger an update because it only checks (o, n) => o.value === n.value. The event handler inside Item uses the old items value.



    It can be fixed with functional updates:



    const valueChanged = (i, newVal) => 
    setItems(oldItems =>
    let updatedItems = [...oldItems];
    updatedItems[i].title = newVal;
    return updatedItems;
    );



    So valueChanged doesn't depend on items and doesn't need to be checked by memo.



    Your code might have similar problems with other handlers. It is better to use functional updates whenener new value is based on the old one.






    share|improve this answer




















    • 1





      Ah, ok. That's kind of what I thought... Thanks a lot.

      – Ivannnnn
      Mar 27 at 16:23











    • I am liking this answer as well. Seems to solve the issue another way.

      – Jacob
      Mar 27 at 16:23













    4












    4








    4







    valueChanged is a closure which gets a fresh items every render. But your memo doesn't trigger an update because it only checks (o, n) => o.value === n.value. The event handler inside Item uses the old items value.



    It can be fixed with functional updates:



    const valueChanged = (i, newVal) => 
    setItems(oldItems =>
    let updatedItems = [...oldItems];
    updatedItems[i].title = newVal;
    return updatedItems;
    );



    So valueChanged doesn't depend on items and doesn't need to be checked by memo.



    Your code might have similar problems with other handlers. It is better to use functional updates whenener new value is based on the old one.






    share|improve this answer













    valueChanged is a closure which gets a fresh items every render. But your memo doesn't trigger an update because it only checks (o, n) => o.value === n.value. The event handler inside Item uses the old items value.



    It can be fixed with functional updates:



    const valueChanged = (i, newVal) => 
    setItems(oldItems =>
    let updatedItems = [...oldItems];
    updatedItems[i].title = newVal;
    return updatedItems;
    );



    So valueChanged doesn't depend on items and doesn't need to be checked by memo.



    Your code might have similar problems with other handlers. It is better to use functional updates whenener new value is based on the old one.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 27 at 16:14









    UjinT34UjinT34

    2,4801 gold badge3 silver badges16 bronze badges




    2,4801 gold badge3 silver badges16 bronze badges










    • 1





      Ah, ok. That's kind of what I thought... Thanks a lot.

      – Ivannnnn
      Mar 27 at 16:23











    • I am liking this answer as well. Seems to solve the issue another way.

      – Jacob
      Mar 27 at 16:23












    • 1





      Ah, ok. That's kind of what I thought... Thanks a lot.

      – Ivannnnn
      Mar 27 at 16:23











    • I am liking this answer as well. Seems to solve the issue another way.

      – Jacob
      Mar 27 at 16:23







    1




    1





    Ah, ok. That's kind of what I thought... Thanks a lot.

    – Ivannnnn
    Mar 27 at 16:23





    Ah, ok. That's kind of what I thought... Thanks a lot.

    – Ivannnnn
    Mar 27 at 16:23













    I am liking this answer as well. Seems to solve the issue another way.

    – Jacob
    Mar 27 at 16:23





    I am liking this answer as well. Seems to solve the issue another way.

    – Jacob
    Mar 27 at 16:23













    0













    You can try initializing the state this way, I tried it on codesandbox and it may be the behavior you are looking for.



    https://codesandbox.io/s/q8l6m2lj64



     const [items, setItems] = useState(() => [
    key: randomStr(), title: 'abc' ,
    key: randomStr(), title: 'def' ,
    ]);





    share|improve this answer





























      0













      You can try initializing the state this way, I tried it on codesandbox and it may be the behavior you are looking for.



      https://codesandbox.io/s/q8l6m2lj64



       const [items, setItems] = useState(() => [
      key: randomStr(), title: 'abc' ,
      key: randomStr(), title: 'def' ,
      ]);





      share|improve this answer



























        0












        0








        0







        You can try initializing the state this way, I tried it on codesandbox and it may be the behavior you are looking for.



        https://codesandbox.io/s/q8l6m2lj64



         const [items, setItems] = useState(() => [
        key: randomStr(), title: 'abc' ,
        key: randomStr(), title: 'def' ,
        ]);





        share|improve this answer













        You can try initializing the state this way, I tried it on codesandbox and it may be the behavior you are looking for.



        https://codesandbox.io/s/q8l6m2lj64



         const [items, setItems] = useState(() => [
        key: randomStr(), title: 'abc' ,
        key: randomStr(), title: 'def' ,
        ]);






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 27 at 16:22









        JacobJacob

        3842 silver badges13 bronze badges




        3842 silver badges13 bronze badges






























            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%2f55381648%2flist-updates-incorrectly%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

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현