Search data using axios in React using a Laravel API

Viewed 543

I'm using React and Laravel to make an application. I managed to display data using Axios in a component, and managed to search data separatly in another component using this code :

const [data,setData]=useState([]);
    
async function search(key)
    {
        console.warn(key)
        let result = await fetch("http://localhost:8000/api/search/"+key);
        result = await result.json();
        console.warn(result)
        setData(result)
    }

The problem is that I can't manage to combine between search and displaying data in a single component. How to do so ? I'm using a personal Laravel API.

JS Component of display data ( Without search ):

import React, { Component } from "react";
import axios from "axios";
import { Container, Dropdown, ListGroup, Button } from "react-bootstrap";
import { Table, Thead, Tbody, Tr, Th, Td } from "react-super-responsive-table";

class Patient extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      patients: [],
    };
  }

  componentDidMount() {
    axios
      .get("api/patients")
      .then((response) => {
        this.setState({ patients: response.data });
      })
      .catch((err) => console.log(err));
  }

  render() {
    return (
      <div>
        <Container>
         
          <div className="form-group">
            <label htmlFor="exampleInputEmail1">Search</label>
            <input
              type="text"
              className="form-control"
              id=" "
              placeholder="Search"
              id="name"
            />
          </div>

          <Table className="table table-hover">
            <Thead className="thead-light text-center">
              <Tr>
                <Th>ID</Th>
                <Th>NAME</Th>
                <Th>FIRST NAME</Th>
              </Tr>
            </Thead>
            <Tbody className="text-center">
              {this.state.patients.reverse().map((patient) => (
                <Tr>
                  <Td>
                    <b>{patient.id}</b>
                  </Td>
                  <Td>
                    <b>{patient.firstname}</b>
                  </Td>
                  <Td>
                    <b>{patient.lastname}</b>
                  </Td>
                </Tr>
              ))}
            </Tbody>
          </Table>
        </Container>
        );
      </div>
    );
  }
}

export default Patient;

My Laravel Controller to search :

  public function search($key)
    {
        return Patient::where('name','Like',"%$key%")->get();
    }

Laravel Route :

Route::get('/search/{key}/', [PatientController::class, 'search']);
0 Answers
Related