Search code examples
javascriptreactjsreact-router-domrefreact-ref

this.props.history.push is working just after refresh


I have a react-big-calendar, which has a button when I click on it, his modal will appear, and I have also a calendar icon button which redirects me to another URL /planning.

I have a dialog (AjouterDisponibilite) and I call it with the ref on my component Agenda.

And the calendar icon has an onClick event which I try:

this.props.history.push('/planning'); 

but when I run it and I click on the icon, the URL is directed correct, but I get an error as shown below:

TypeError: Cannot read property 'handleAjouter' of null and Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method

and after I refresh this page, it works.

My code is: https://codesandbox.io/s/xw01v53oz

How can I fix it?


Solution

  • The problem is improper use of Refs. Refs are designed to keep references to DOM-elements and component instances, not their functions.

    Components with a ref prop will assign themself to the value of the prop (or call the function with itself as an argument) when they are mounted, and they will do the same with a null reference when they are unmounted.

    With this knowledge, you have to change your code of the Agenda component as follows:

    ModalAjout = (ref) => {
        if (ref) {
            this.ajout = ref.handleAjouter;
        } else {
            this.ajout = null;
        }
    }
    
    ModalAjoutb = (ref) => {
        if (ref) {
            this.ajoutb = ref.handleAjouter;
        } else {
            this.ajoutb = null;
        }
    }