I'm creating a frontend for an API that I made, I'm using React as the frontend. When I try to use componentDidMount(){} I get a syntax error that says expected ;. The ; is expected between the ) and {. What seems to be the issue?

P.S. I'm using visual studio code - exploration

I tried to insert the semicolon, but that led to more problems.

import React from 'react';
import './App.css';

function App() {

  state = {
    students: []
  }

  componentDidMount(){
    this.getStudents();
  }

  getStudents = _ => {
    fetch('http://localhost:4000/students')
    .then(response => response.json())
    .then(response => this.setState({students: response.data}))
    .catch(err => console.error(err))
  }

  renderStudent = ({student_id, name}) => <div key={student_id}>{name}</div>

  return (
    <div className="App">
      {students.map(this.renderStudent)}
    </div>
  );
}

export default App;

3 Answers

0
jens On Best Solutions

You are mixxing class syntax into a component declared as a function. The componentDidMount is a method on a class component. So even adding function before it, which would fix your syntax issue, wouldn’t give you the result you are looking for.

With functions use hooks, or switch to A class based component.

0
Tomer Levi On

componentDidMount() is an React Component API whereas you are using a function component that doesn't have this API to be used.

0
M.Gumede On

It worked..i changed function App () to class App extends Component. Thanks for the help.