React state is out of sync between render method and what is actually displayed on page










1















I need to access DOM elements outside of my React app, which may load slower than my app. Then I need to update my state to render a few different things. To do that I am polling for the DOM elements with a recursive function that gets kicked off from componentDidMount(). I'm seeing a weird issue where once the element is found and I've updated the state, things get out of sync. In the render function, my console.log() shows the updated state value, in React Developer Tools I see the updated state value, but on the actual rendered page I see still see the old state value.



Code:



// initially doesn't exist. Added to the DOM after 3 seconds
let slowElement = document.querySelector('.external-dom-element')

class App extends React.Component
constructor (props)
super(props)

this.state =
showFoundSlowElementMessage: false,
slowElementCheckMaxAttempts: 5,
slowElementCheckCount: 0,


this.checkForSlowElement = this.checkForSlowElement.bind(this)


componentDidMount ()
this.checkForSlowElement()


checkForSlowElement ()
slowElement = document.querySelector('.external-dom-element')

if (slowElement !== null)
console.log('found') // element found, show message

this.setState(
showFoundSlowElementMessage: true
)
else
console.log('not found') // element not found, increment count and check again after delay

this.setState(
slowElementCheckCount: this.state.slowElementCheckCount + 1
, () =>
if (this.state.slowElementCheckCount < this.state.slowElementCheckMaxAttempts)
window.setTimeout(this.checkForSlowElement, 1000)

)



render()
const foundSlowElement = this.state.showFoundSlowElementMessage
? <p>Found slow element</p>
: <p>No sign of slow element, checked this.state.slowElementCheckCount times</p>

// null until it is added to the page
console.log(foundSlowElement)

return (
<div>
<h1>Hello</h1>
foundSlowElement
</div>
);


}

ReactDOM.render(<App />, document.getElementById('react-target'));

// Simulate slow element by adding it to the DOM after 3 seconds
window.setTimeout(() =>
const root = document.getElementById('root');
const newElement = '<div class="external-dom-element">slow element</div>';
root.innerHTML += newElement;
, 3000)


Working example on codepen










share|improve this question




























    1















    I need to access DOM elements outside of my React app, which may load slower than my app. Then I need to update my state to render a few different things. To do that I am polling for the DOM elements with a recursive function that gets kicked off from componentDidMount(). I'm seeing a weird issue where once the element is found and I've updated the state, things get out of sync. In the render function, my console.log() shows the updated state value, in React Developer Tools I see the updated state value, but on the actual rendered page I see still see the old state value.



    Code:



    // initially doesn't exist. Added to the DOM after 3 seconds
    let slowElement = document.querySelector('.external-dom-element')

    class App extends React.Component
    constructor (props)
    super(props)

    this.state =
    showFoundSlowElementMessage: false,
    slowElementCheckMaxAttempts: 5,
    slowElementCheckCount: 0,


    this.checkForSlowElement = this.checkForSlowElement.bind(this)


    componentDidMount ()
    this.checkForSlowElement()


    checkForSlowElement ()
    slowElement = document.querySelector('.external-dom-element')

    if (slowElement !== null)
    console.log('found') // element found, show message

    this.setState(
    showFoundSlowElementMessage: true
    )
    else
    console.log('not found') // element not found, increment count and check again after delay

    this.setState(
    slowElementCheckCount: this.state.slowElementCheckCount + 1
    , () =>
    if (this.state.slowElementCheckCount < this.state.slowElementCheckMaxAttempts)
    window.setTimeout(this.checkForSlowElement, 1000)

    )



    render()
    const foundSlowElement = this.state.showFoundSlowElementMessage
    ? <p>Found slow element</p>
    : <p>No sign of slow element, checked this.state.slowElementCheckCount times</p>

    // null until it is added to the page
    console.log(foundSlowElement)

    return (
    <div>
    <h1>Hello</h1>
    foundSlowElement
    </div>
    );


    }

    ReactDOM.render(<App />, document.getElementById('react-target'));

    // Simulate slow element by adding it to the DOM after 3 seconds
    window.setTimeout(() =>
    const root = document.getElementById('root');
    const newElement = '<div class="external-dom-element">slow element</div>';
    root.innerHTML += newElement;
    , 3000)


    Working example on codepen










    share|improve this question


























      1












      1








      1


      0






      I need to access DOM elements outside of my React app, which may load slower than my app. Then I need to update my state to render a few different things. To do that I am polling for the DOM elements with a recursive function that gets kicked off from componentDidMount(). I'm seeing a weird issue where once the element is found and I've updated the state, things get out of sync. In the render function, my console.log() shows the updated state value, in React Developer Tools I see the updated state value, but on the actual rendered page I see still see the old state value.



      Code:



      // initially doesn't exist. Added to the DOM after 3 seconds
      let slowElement = document.querySelector('.external-dom-element')

      class App extends React.Component
      constructor (props)
      super(props)

      this.state =
      showFoundSlowElementMessage: false,
      slowElementCheckMaxAttempts: 5,
      slowElementCheckCount: 0,


      this.checkForSlowElement = this.checkForSlowElement.bind(this)


      componentDidMount ()
      this.checkForSlowElement()


      checkForSlowElement ()
      slowElement = document.querySelector('.external-dom-element')

      if (slowElement !== null)
      console.log('found') // element found, show message

      this.setState(
      showFoundSlowElementMessage: true
      )
      else
      console.log('not found') // element not found, increment count and check again after delay

      this.setState(
      slowElementCheckCount: this.state.slowElementCheckCount + 1
      , () =>
      if (this.state.slowElementCheckCount < this.state.slowElementCheckMaxAttempts)
      window.setTimeout(this.checkForSlowElement, 1000)

      )



      render()
      const foundSlowElement = this.state.showFoundSlowElementMessage
      ? <p>Found slow element</p>
      : <p>No sign of slow element, checked this.state.slowElementCheckCount times</p>

      // null until it is added to the page
      console.log(foundSlowElement)

      return (
      <div>
      <h1>Hello</h1>
      foundSlowElement
      </div>
      );


      }

      ReactDOM.render(<App />, document.getElementById('react-target'));

      // Simulate slow element by adding it to the DOM after 3 seconds
      window.setTimeout(() =>
      const root = document.getElementById('root');
      const newElement = '<div class="external-dom-element">slow element</div>';
      root.innerHTML += newElement;
      , 3000)


      Working example on codepen










      share|improve this question
















      I need to access DOM elements outside of my React app, which may load slower than my app. Then I need to update my state to render a few different things. To do that I am polling for the DOM elements with a recursive function that gets kicked off from componentDidMount(). I'm seeing a weird issue where once the element is found and I've updated the state, things get out of sync. In the render function, my console.log() shows the updated state value, in React Developer Tools I see the updated state value, but on the actual rendered page I see still see the old state value.



      Code:



      // initially doesn't exist. Added to the DOM after 3 seconds
      let slowElement = document.querySelector('.external-dom-element')

      class App extends React.Component
      constructor (props)
      super(props)

      this.state =
      showFoundSlowElementMessage: false,
      slowElementCheckMaxAttempts: 5,
      slowElementCheckCount: 0,


      this.checkForSlowElement = this.checkForSlowElement.bind(this)


      componentDidMount ()
      this.checkForSlowElement()


      checkForSlowElement ()
      slowElement = document.querySelector('.external-dom-element')

      if (slowElement !== null)
      console.log('found') // element found, show message

      this.setState(
      showFoundSlowElementMessage: true
      )
      else
      console.log('not found') // element not found, increment count and check again after delay

      this.setState(
      slowElementCheckCount: this.state.slowElementCheckCount + 1
      , () =>
      if (this.state.slowElementCheckCount < this.state.slowElementCheckMaxAttempts)
      window.setTimeout(this.checkForSlowElement, 1000)

      )



      render()
      const foundSlowElement = this.state.showFoundSlowElementMessage
      ? <p>Found slow element</p>
      : <p>No sign of slow element, checked this.state.slowElementCheckCount times</p>

      // null until it is added to the page
      console.log(foundSlowElement)

      return (
      <div>
      <h1>Hello</h1>
      foundSlowElement
      </div>
      );


      }

      ReactDOM.render(<App />, document.getElementById('react-target'));

      // Simulate slow element by adding it to the DOM after 3 seconds
      window.setTimeout(() =>
      const root = document.getElementById('root');
      const newElement = '<div class="external-dom-element">slow element</div>';
      root.innerHTML += newElement;
      , 3000)


      Working example on codepen







      javascript reactjs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 14 '18 at 15:09







      blinco

















      asked Nov 14 '18 at 14:48









      blincoblinco

      62




      62






















          1 Answer
          1






          active

          oldest

          votes


















          0














          I figured this out myself. It has nothing to do with my component, it's the demo itself that is breaking it. When I simulate the slow element by appending the root element's inner html:



           root.innerHTML += newElement;


          It re-parses the the entire element and React loses all of the event handlers, etc. that it had previously set up.



          This thread helped me out






          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%2f53302893%2freact-state-is-out-of-sync-between-render-method-and-what-is-actually-displayed%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









            0














            I figured this out myself. It has nothing to do with my component, it's the demo itself that is breaking it. When I simulate the slow element by appending the root element's inner html:



             root.innerHTML += newElement;


            It re-parses the the entire element and React loses all of the event handlers, etc. that it had previously set up.



            This thread helped me out






            share|improve this answer



























              0














              I figured this out myself. It has nothing to do with my component, it's the demo itself that is breaking it. When I simulate the slow element by appending the root element's inner html:



               root.innerHTML += newElement;


              It re-parses the the entire element and React loses all of the event handlers, etc. that it had previously set up.



              This thread helped me out






              share|improve this answer

























                0












                0








                0







                I figured this out myself. It has nothing to do with my component, it's the demo itself that is breaking it. When I simulate the slow element by appending the root element's inner html:



                 root.innerHTML += newElement;


                It re-parses the the entire element and React loses all of the event handlers, etc. that it had previously set up.



                This thread helped me out






                share|improve this answer













                I figured this out myself. It has nothing to do with my component, it's the demo itself that is breaking it. When I simulate the slow element by appending the root element's inner html:



                 root.innerHTML += newElement;


                It re-parses the the entire element and React loses all of the event handlers, etc. that it had previously set up.



                This thread helped me out







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 14 '18 at 15:53









                blincoblinco

                62




                62



























                    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%2f53302893%2freact-state-is-out-of-sync-between-render-method-and-what-is-actually-displayed%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

                    Top Tejano songwriter Luis Silva dead of heart attack at 64

                    政党

                    天津地下鉄3号線