Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda