Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

componentDidMount() not being called when react component is mounted

Tags:

reactjs

I've been attempting to fetch some data from a server and for some odd reason componentDidMount() is not firing as it should be. I added a console.log() statement inside of componentDidMount() to check if it was firing. I know the request to the server works as it should As I used it outside of react and it worked as it should.

class App extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      obj: {}
    };
  };

  getAllStarShips () {
    reachGraphQL('http://localhost:4000/', `{
     allStarships(first: 7) {
       edges {
         node {
           id
           name
           model
           costInCredits
           pilotConnection {
             edges {
               node {
                 ...pilotFragment
               }
             }
           }
         }
       }
     }
    }
    fragment pilotFragment on Person {
     name
     homeworld { name }
   }`, {}). then((data) => {
     console.log('getALL:', JSON.stringify(data, null, 2))
      this.setState({
        obj: data
      });
   });
  }

  componentDidMount() {
    console.log('Check to see if firing')
    this.getAllStarShips();
  }

  render() {
    console.log('state:',JSON.stringify(this.state.obj, null, 2));
  return (
    <div>
      <h1>React-Reach!</h1>
      <p>{this.state.obj.allStarships.edges[1].node.name}</p>
    </div>
  );
}

}

render(
  <App></App>,
  document.getElementById('app')
);
like image 859
kennet postigo Avatar asked Mar 09 '16 15:03

kennet postigo


People also ask

Why is componentDidMount not working?

Although you have a console log statement in your componentDidMount function it may not be executing because that function never gets run. If the error occurs before componentDidMount gets called such as in your render function, you won't see the console log.

How do I trigger componentDidMount?

You shouldn't try to trigger componentDidMount on click because componentDidMount is executed only once in the lifecycle of the component, immediately after a component is mounted. You should change onBtNext() function to fetch the data.

How do you call componentDidMount again in React JS?

Conclusion. By default, a React component will only call componentDidMount once. The only way it will get run again is if you delete the component or change the key prop value.

Does componentDidMount () only run once?

In this case componentDidMount() will ONLY run once. Let's look at another example where a React component only triggers componentDidMount() once. In the example above I'm using console. log() to print the render and component did mount lifecycle triggers.


3 Answers

The issue here is that the render method is crashing, because the following line is generating an error

<p>{this.state.obj.allStarships.edges[1].node.name}</p>

Fix this to not use this.state.obj.allStarships.edges[1].node.name directly, unless you can guarantee that each receiver is defined.

like image 60
Jim Pedid Avatar answered Oct 08 '22 01:10

Jim Pedid


Check your component's key

Another thing that will cause this to happen is if your component does not have a key. In React, the key property is used to determine whether a change is just new properties for a component or if the change is a new component.

React will only unmount the old component and mount a new one if the key changed. If you're seeing cases where componentDidMount() is not being called, make sure your component has a unique key.

With the key set, React will interpret them as different components and handle unmounting and mounting.

Example Without a Key:

<SomeComponent prop1={foo} />

Example with a Key

const key = foo.getUniqueId()
<SomeComponent key={key} prop1={foo} />
like image 45
Jon Avatar answered Oct 08 '22 02:10

Jon


Also check that you don't have more than one componentDidMount if you have a component with a lot of code. It's a good idea to keep lifecycle methods near the top after the constructor.

like image 21
Gus T Butt Avatar answered Oct 08 '22 01:10

Gus T Butt