react context with componentdidupdate












0















I am running a pattern like so, the assumption is that SearchResultsContainer is mounted and somewhere a searchbar sets the input.



class SearchResults {
render() {
return(
<ResultsContext.Consumer value={input}>
{input => <SearchResultsContainer input=input}
</ResultsContext.Consumer>
)
}

class SearchResultsContainer
componentDidUpdate() {
//fetch data based on new input
if (check if data is the same) {
this.setState({
data: fetchedData
})
}
}
}


this will invoke a double fetch whenever a new context value has been called, because componentDidUpdate() will fire and set the data. On a new input from the results context, it will invoke componentDidUpdate(), fetch, set data, then invoke componentDidUpdate(), and fetch, then will check if data is the same and stop the loop.



Is this the right way to be using context?










share|improve this question

























  • Would it be possible to check if the context value has changed instead of data and fetch accordingly?

    – o4ohel
    Nov 22 '18 at 4:28











  • I could, that would mean I need to compare the previous context with the current context. And I would have to save the previous context as local state since componentdidupdate doesn't know prevcontext

    – goda
    Nov 22 '18 at 14:59
















0















I am running a pattern like so, the assumption is that SearchResultsContainer is mounted and somewhere a searchbar sets the input.



class SearchResults {
render() {
return(
<ResultsContext.Consumer value={input}>
{input => <SearchResultsContainer input=input}
</ResultsContext.Consumer>
)
}

class SearchResultsContainer
componentDidUpdate() {
//fetch data based on new input
if (check if data is the same) {
this.setState({
data: fetchedData
})
}
}
}


this will invoke a double fetch whenever a new context value has been called, because componentDidUpdate() will fire and set the data. On a new input from the results context, it will invoke componentDidUpdate(), fetch, set data, then invoke componentDidUpdate(), and fetch, then will check if data is the same and stop the loop.



Is this the right way to be using context?










share|improve this question

























  • Would it be possible to check if the context value has changed instead of data and fetch accordingly?

    – o4ohel
    Nov 22 '18 at 4:28











  • I could, that would mean I need to compare the previous context with the current context. And I would have to save the previous context as local state since componentdidupdate doesn't know prevcontext

    – goda
    Nov 22 '18 at 14:59














0












0








0








I am running a pattern like so, the assumption is that SearchResultsContainer is mounted and somewhere a searchbar sets the input.



class SearchResults {
render() {
return(
<ResultsContext.Consumer value={input}>
{input => <SearchResultsContainer input=input}
</ResultsContext.Consumer>
)
}

class SearchResultsContainer
componentDidUpdate() {
//fetch data based on new input
if (check if data is the same) {
this.setState({
data: fetchedData
})
}
}
}


this will invoke a double fetch whenever a new context value has been called, because componentDidUpdate() will fire and set the data. On a new input from the results context, it will invoke componentDidUpdate(), fetch, set data, then invoke componentDidUpdate(), and fetch, then will check if data is the same and stop the loop.



Is this the right way to be using context?










share|improve this question
















I am running a pattern like so, the assumption is that SearchResultsContainer is mounted and somewhere a searchbar sets the input.



class SearchResults {
render() {
return(
<ResultsContext.Consumer value={input}>
{input => <SearchResultsContainer input=input}
</ResultsContext.Consumer>
)
}

class SearchResultsContainer
componentDidUpdate() {
//fetch data based on new input
if (check if data is the same) {
this.setState({
data: fetchedData
})
}
}
}


this will invoke a double fetch whenever a new context value has been called, because componentDidUpdate() will fire and set the data. On a new input from the results context, it will invoke componentDidUpdate(), fetch, set data, then invoke componentDidUpdate(), and fetch, then will check if data is the same and stop the loop.



Is this the right way to be using context?







reactjs lifecycle






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 5:47









EJoshuaS

7,279102949




7,279102949










asked Nov 22 '18 at 0:57









godagoda

86110




86110













  • Would it be possible to check if the context value has changed instead of data and fetch accordingly?

    – o4ohel
    Nov 22 '18 at 4:28











  • I could, that would mean I need to compare the previous context with the current context. And I would have to save the previous context as local state since componentdidupdate doesn't know prevcontext

    – goda
    Nov 22 '18 at 14:59



















  • Would it be possible to check if the context value has changed instead of data and fetch accordingly?

    – o4ohel
    Nov 22 '18 at 4:28











  • I could, that would mean I need to compare the previous context with the current context. And I would have to save the previous context as local state since componentdidupdate doesn't know prevcontext

    – goda
    Nov 22 '18 at 14:59

















Would it be possible to check if the context value has changed instead of data and fetch accordingly?

– o4ohel
Nov 22 '18 at 4:28





Would it be possible to check if the context value has changed instead of data and fetch accordingly?

– o4ohel
Nov 22 '18 at 4:28













I could, that would mean I need to compare the previous context with the current context. And I would have to save the previous context as local state since componentdidupdate doesn't know prevcontext

– goda
Nov 22 '18 at 14:59





I could, that would mean I need to compare the previous context with the current context. And I would have to save the previous context as local state since componentdidupdate doesn't know prevcontext

– goda
Nov 22 '18 at 14:59












1 Answer
1






active

oldest

votes


















0














The solution I used is to transfer the context to the props through a High Order Component.



I have used this very usefull github answer https://github.com/facebook/react/issues/12397#issuecomment-374004053



The result looks Like this :
my-context.js :



import React from "react";

export const MyContext = React.createContext({ foo: 'bar' });

export const withMyContext = Element => {
return React.forwardRef((props, ref) => {
return (
<MyContext.Consumer>
{context => <Element myContext={context} {...props} ref={ref} />}
</MyContext.Consumer>
);
});
};


An other component that consumes the context :



import { withMyContext } from "./path/to/my-context";

class MyComponent extends Component {
componentDidUpdate(prevProps) {
const {myContext} = this.props
if(myContext.foo !== prevProps.myContext.foo){
this.doSomething()
}
}
}
export default withMyContext(MyComponent);


There must be a context producer somewhere :



<MyContext.Provider value={{ foo: this.state.foo }}>
<MyComponent />
</MyContext.Provider>






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%2f53422502%2freact-context-with-componentdidupdate%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














    The solution I used is to transfer the context to the props through a High Order Component.



    I have used this very usefull github answer https://github.com/facebook/react/issues/12397#issuecomment-374004053



    The result looks Like this :
    my-context.js :



    import React from "react";

    export const MyContext = React.createContext({ foo: 'bar' });

    export const withMyContext = Element => {
    return React.forwardRef((props, ref) => {
    return (
    <MyContext.Consumer>
    {context => <Element myContext={context} {...props} ref={ref} />}
    </MyContext.Consumer>
    );
    });
    };


    An other component that consumes the context :



    import { withMyContext } from "./path/to/my-context";

    class MyComponent extends Component {
    componentDidUpdate(prevProps) {
    const {myContext} = this.props
    if(myContext.foo !== prevProps.myContext.foo){
    this.doSomething()
    }
    }
    }
    export default withMyContext(MyComponent);


    There must be a context producer somewhere :



    <MyContext.Provider value={{ foo: this.state.foo }}>
    <MyComponent />
    </MyContext.Provider>






    share|improve this answer




























      0














      The solution I used is to transfer the context to the props through a High Order Component.



      I have used this very usefull github answer https://github.com/facebook/react/issues/12397#issuecomment-374004053



      The result looks Like this :
      my-context.js :



      import React from "react";

      export const MyContext = React.createContext({ foo: 'bar' });

      export const withMyContext = Element => {
      return React.forwardRef((props, ref) => {
      return (
      <MyContext.Consumer>
      {context => <Element myContext={context} {...props} ref={ref} />}
      </MyContext.Consumer>
      );
      });
      };


      An other component that consumes the context :



      import { withMyContext } from "./path/to/my-context";

      class MyComponent extends Component {
      componentDidUpdate(prevProps) {
      const {myContext} = this.props
      if(myContext.foo !== prevProps.myContext.foo){
      this.doSomething()
      }
      }
      }
      export default withMyContext(MyComponent);


      There must be a context producer somewhere :



      <MyContext.Provider value={{ foo: this.state.foo }}>
      <MyComponent />
      </MyContext.Provider>






      share|improve this answer


























        0












        0








        0







        The solution I used is to transfer the context to the props through a High Order Component.



        I have used this very usefull github answer https://github.com/facebook/react/issues/12397#issuecomment-374004053



        The result looks Like this :
        my-context.js :



        import React from "react";

        export const MyContext = React.createContext({ foo: 'bar' });

        export const withMyContext = Element => {
        return React.forwardRef((props, ref) => {
        return (
        <MyContext.Consumer>
        {context => <Element myContext={context} {...props} ref={ref} />}
        </MyContext.Consumer>
        );
        });
        };


        An other component that consumes the context :



        import { withMyContext } from "./path/to/my-context";

        class MyComponent extends Component {
        componentDidUpdate(prevProps) {
        const {myContext} = this.props
        if(myContext.foo !== prevProps.myContext.foo){
        this.doSomething()
        }
        }
        }
        export default withMyContext(MyComponent);


        There must be a context producer somewhere :



        <MyContext.Provider value={{ foo: this.state.foo }}>
        <MyComponent />
        </MyContext.Provider>






        share|improve this answer













        The solution I used is to transfer the context to the props through a High Order Component.



        I have used this very usefull github answer https://github.com/facebook/react/issues/12397#issuecomment-374004053



        The result looks Like this :
        my-context.js :



        import React from "react";

        export const MyContext = React.createContext({ foo: 'bar' });

        export const withMyContext = Element => {
        return React.forwardRef((props, ref) => {
        return (
        <MyContext.Consumer>
        {context => <Element myContext={context} {...props} ref={ref} />}
        </MyContext.Consumer>
        );
        });
        };


        An other component that consumes the context :



        import { withMyContext } from "./path/to/my-context";

        class MyComponent extends Component {
        componentDidUpdate(prevProps) {
        const {myContext} = this.props
        if(myContext.foo !== prevProps.myContext.foo){
        this.doSomething()
        }
        }
        }
        export default withMyContext(MyComponent);


        There must be a context producer somewhere :



        <MyContext.Provider value={{ foo: this.state.foo }}>
        <MyComponent />
        </MyContext.Provider>







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 17 at 12:04









        Stephane LStephane L

        584511




        584511
































            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%2f53422502%2freact-context-with-componentdidupdate%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

            If I really need a card on my start hand, how many mulligans make sense? [duplicate]

            Alcedinidae

            Can an atomic nucleus contain both particles and antiparticles? [duplicate]