Tags
react.js
Asked 2 years ago
20 Jul 2022
Views 681

posted

ReactJS - how to fetch data from api ?

how to fetch data from an api in ReactJS ?
Phpworker

Phpworker
answered Jun 10 '21 00:00

axios
Use axios , to fetch api or for ajax call from react js or react native

install axios by any suitable command based on your environment:

Using npm:

npm install axios

Using bower:

bower install axios

Using yarn:

yarn add axios

Using pnpm:

pnpm add axios

Using jsDelivr CDN:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Using unpkg CDN:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


after installation import axios in your component

import axios from "axios"




POST METHOD API CALL


call api by POST Method :

axios.post('mywebsite.com/login.php', {
    username: 'mit',
    password: '123'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });


or same call done by


axios(  method: 'post',
  url: 'mywebsite.com/login.php',
  data: {
    username: 'mit',
    password: '123'
  }
 )
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });



call api by GET Method :


axios({
  method: 'get',
  url: 'userdetail/123',
 })
  .then(function (response) {
     console.log(response);
  });

or shorthand for get method

axios('/userdetail/1234');

default method is get method .


so you need to define the method , url and call back function which called after api call completion

so either you can use defualt axios function

axios(config)


config object have url , method and other properties

or other syntax for axios call for all type of request as below:

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])


axios support all latest browser.

more detail about axios
kord

kord
answered Jun 10 '21 00:00

fetch api
you can put fetch api call in componentDidMount function in the component so it will call api after componentmount

i use fetch method from api ,
i use here get method to get product detail from product api


 fetch("https://api.com/products/"+this.props.productid)
        .then(res => res.json())
        .then(
          (result) => {
		  console.log(result); 
	    this.setState({ items: result }); 
 
          }
        ); 


so lets say we are making a Featureproduct component and we are trying to get featured products from api
so component code will be like as below :


class Featureproduct extends React.Component{
    constructor(props) {
    super(props);
       this.state = { items: [], text: '' };
 
  }
  componentWillMount(){
 fetch("https://api.com/products/"+this.props.productid)
        .then(res => res.json())
        .then(
          (result) => {
		  console.log(result); 
	    this.setState({ items: result }); 
 
          }
        ); 
}


  render() {
      
    return (
       <><div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative">
        <div class="col p-4 d-flex flex-column position-static">
          <strong class="d-inline-block mb-2 text-primary">{this.state.items.category}</strong>
          <p class="card-text mb-auto"> {this.state.items.title}</p>
          <div class="mb-1 text-muted">{"$"+this.state.items.price}</div>
          <a href="#" class="stretched-link">Continue reading</a>
 

        </div>
        <div class="col-auto d-none d-lg-block">
          <img   src={this.state.items.image}  width="200px" height="200px" />
        </div>
      </div></>
    );
  }
}


denyy

denyy
answered Jun 10 '21 00:00

calls api in the componentDidMount lifecycle method. This is so you can use setState to update your component when the data is retrieved.

or calls api in the useEffect
Post Answer