1
import React from 'react'

componentDidMount(){
    fetch(`https://jsonplaceholder.com/users/`)
    .then(res => res.hson())
    .then(res => {
        .console.log(res)
    })
}

const App  = () => {
    return (
        <h1>Hello</h1>
    )
}

export default App; 

How to make api call in react function based view.

Here it is saying componentDidMount not found.

Is there any way to make api call using function based view.

Please have a look

2 Answers2

2

React 16.8 has useEffect Hook.

import React, { useState, useEffect} from 'react';
const App  = () => {
    const [data, setData] = useState('');
    useEffect(() => {
      fetch(`https://jsonplaceholder.com/users/`)
      .then(res => res.hson())
      .then(res => {
       setData(res);
      })
    });
    return (
        <h1>Hello</h1>
    )
}
ravibagul91
  • 20,072
  • 5
  • 36
  • 59
0

componentDidMount should be inside class component.

import React, {Component} from 'react'


class App extends Component  {

    componentDidMount(){
    fetch(`https://jsonplaceholder.com/users/`)
    .then(res => res.hson())
    .then(res => {
        .console.log(res)
    })


    render() {
    return (
        <h1>Hello</h1>
    )
}

}

export default App; 
Anil Kumar
  • 2,223
  • 2
  • 17
  • 22