Calling api in react with axios and search but don't know how to do it

94 views Asked by At

So here is the thing. I have the endpoint but don't know how to filter the response and list the result in the same way for every object.

I know this a very newbie intro question, I appreciate any article that you guys think that can help.

import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import '../assets/styles/Shared.css';
import { MDBBtn } from 'mdbreact';
/////
import axios from 'axios';
import api from '../services/api';

class Home extends React.Component {
  render() {
    return (
      <>
        <div className="CallApi">
          <div className="container">
            <h1 className="logo"></h1>

            <h1 className="search">
              <input className="form-control mr-sm-2" type="text" placeholder="Search for vehicle" onClick={null} />
              <MDBBtn color="unique" rounded size="sm" type="submit" className="mr-auto">
                Pesquisar
              </MDBBtn>
              <h1 className="hometext">THE SEARCH FOR THE VEHICLES</h1>
            </h1>
          </div>
        </div>
      </>
    );
  }
}

export default Home;

The data format is:

  {
    "id": "1",
    "title": "title 1",
    "model": "model 1",
    "brand": "brand 1",
    "year": 69,
    "color": 19,
    "km": 79,
    "price": 99
  },
1

There are 1 answers

0
Gabriel Ferrari On

To work with the returned JSON, you can use the function map().

You should filter the data in your backend because load all the information in frontend could make your app slow, but you can the function filter.

  const search = () => {
    axios.get(`${YOUR_URL}`)
      .then(res => {
        return res.data
      })
  }

  return (
    <>
    {search().map((item) => {
      return(
        <h1>{ item.title }</h1>
        )
      })}
  </>
  )