Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

100
Vistas
Update a React Element with the Data of Another Component's API Response

I am trying to make a simple react app that pulls info from a MySQL database ("username", "balance", "purchases").

So far, I've used node and react to pull from the database with an HTTP query and to display each element on the website.

I then created the API query for searching the database for all entries that start with what I've typed into the search bar.

The issue I'm running into is how do I change the state of the elements that display the username, etc with the new filtered information from the API query? The search bar and data elements are two separate components so I can't use the use effect hook natively.

I cant use the filter method because the database is huge and I've sent my query limit to 100.

Here's my code so far:

  PlayerData.js
    
import axios from 'axios';
import React,{useState, useEffect} from 'react';

    
const Player = () => {
  const [playerData,setPlayerData]=useState([])

  useEffect(()=>{
    axios.get("http://localhost:3001/api/get").then((res)=>{
    console.log(res.data)
    setPlayerData(res.data)
    })
      .catch(err=>{
        console.log(err);
      })
  },[])

    return (
      <>
      {playerData.map((data,id)=>{
        return <div className="Player" key={id}>
          <span className="Username"> { data.name }  </span> 
          <span className="Crystals"> { data.balance }  </span> 
          <span className="DateModi"> {Object.keys(JSON.parse(data.items)).length}  </span>
        </div>
      })}
  
      </>

    )
};

export default Player;

SearchBar.js


import { useState } from "react";
import axios from 'axios'

const Search = () => {
    const [searchTerm, setSearchTerm] = useState("")
    axios.get(`http://localhost:3001/api/getSearchName/${searchTerm}`).then((res)=>{
    console.log(res.data)
    })
    return (
        <div className="Search">
   
          <input className = "InputField" type="text" placeholder="Enter Username:" onChange={e => {setSearchTerm(e.target.value)}}/>
          <span className="SearchButton" onClick={console.log(searchTerm)}>
                Search
            </span>

    </div>
    )
};

export default Search;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If I understood the question correctly, you need to set the state of PlayerData to a shared component(App), and pass it to the Player.js component. Then when searching it will be overwritten and update the information in the Player.js

function App() {
  const [playerData, setPlayerData] = useState([]);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = () =>
    axios
      .get("http://localhost:3001/api/get")
      .then((res) => {
        setPlayerData(res.data);
      })
      .catch((err) => {
        console.log(err);
      });

  const handleSearch = (text) => {
    const clearText = text.trim();
    if (!clearText.length) {
      fetchData();
      return;
    }
    axios
      .get(`http://localhost:3001/api/getSearchName/${clearText}`)
      .then((res) => {
        setPlayerData(res.data);
      });
  };

  return (
    <div>
      <div>
        <Search handleSearch={handleSearch} />
      </div>
      <div>
        <Player playerData={playerData} />
      </div>
    </div>
  );
}

Search.js

const Search = ({ handleSearch }) => {
  const [searchTerm, setSearchTerm] = useState("");

  return (
    <div className="Search">
      <input
        className="InputField"
        type="text"
        placeholder="Enter Username:"
        onChange={(e) => {
          setSearchTerm(e.target.value);
        }}
      />
      <span className="SearchButton" onClick={() => handleSearch(searchTerm)}>
        Search
      </span>
    </div>
  );
};

Player.js

const Player = ({ playerData }) => {
  return (
    <>
      {playerData?.length ? (
        playerData.map((data, id) => {
          return (
            <div className="Player" key={id}>
              <span className="Username"> {data.name} </span>
              <span className="Crystals"> {data.balance} </span>
              <span className="DateModi">
                {" "}
                {Object.keys(JSON.parse(data.items)).length}{" "}
              </span>
            </div>
          );
        })
      ) : (
        <div>Loading...</div>
      )}
    </>
  );
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda