1
votes

I am new in React . I am trying to get my api data with axios . But getting error . My code are :

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import ApiContent from './ApiContent';

class App extends React.Component{
    axios.get('http://example.com/api/api/topCardNews')
      .then(function (response) {
        // handle success
        console.log(response);
      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .then(function () {
        // always executed
      });

    render() {
        return(
            <div className="asdfs">
                <ApiContent />
            </div>
        );
    }
}

ReactDOM.render(<App />,document.getElementById('root'));

And Getting the errors Lists of :

Failed to compile

./src/index.js Syntax error: Unexpected token (7:7)

6 | class App extends React.Component{

7 | axios.get('http://example.com/api/api/topCardNews')

8 | .then(function (response) {

9 | // handle success

10 | console.log(response);

This error occurred during the build time and cannot be dismissed.
3
you are attempting to call a function inside a class declaration. put your function call inside the class constructor or a class instance method. - Dan O
@DanO I am sorry for that let me try this with constructor - MD. Jubair Mizan

3 Answers

2
votes

Put call function inside constructor or componentDidMount function like

class App extends React.Component{
    constructor(props) {
     super(props);
     axios.get('http://example.com/api/api/topCardNews') //...
    }

    componentDidMount(){
      //or here or to other lifecycle function based on needs
    }


    render() {
        return(
            <div className="asdfs">
                <ApiContent />
            </div>
        );
    }
}
1
votes

You should be calling the axios.get(.....) in either life cycle events (like ComponentWillMount) or Constructor.

A class component can either have declarations or function definitions along with render. It cannot have direct call to a function.

0
votes

The problem is i have to use this api code inside any Javascript event or constructor().

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import ApiContent from './ApiContent';

class App extends React.Component{
    constructor(props){
        super(props);
        axios.get('http://example.com/api/topCardNews')
          .then(function (response) {
            // handle success
            console.log(response);
          })
          .catch(function (error) {
            // handle error
            console.log(error);
          })
          .then(function () {
            // always executed
          });
    }

    render() {
        return(
            <div className="asdfs">
                <ApiContent />
            </div>
        );
    }
}

ReactDOM.render(<App />,document.getElementById('root'));