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

188
Visualizações
How can I take the previous 5 values I am passing through search and then using it in API. I want to display pervious five values

This is a functional component. Here I am using useEffect hook to hit API on the dependency of search. The place where I am doing console.log(${search} is displaying the current search in the console. How can I take the last five searches in an array and then display them?

    const [city, setCity] = useState(null);
    const [search, setSearch] = useState("Dehradun");


useEffect ( () => {
        const fetchApi = async () => {
            const url = `https://api.openweathermap.org/data/2.5/weather?q=${search}&units=metric&appid=7938d9005e68d8b258a109c716436c91`
            const response = await fetch(url);
            fetch("https://api.openweathermap.org/data/2.5/weather?q=${search}&units=metric&appid=7938d9005e68d8b258a109c716436c91")
            .then(result => console.log(`${search}`, result))
            const resJson = await response.json();
            setCity(resJson.main);
        };
        fetchApi();

    },[search] )```
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The following code is able to keep track of previous searches as you expect. It just stacks the previous response to an array along with the result and excludes items from the end when the size exceeds more than 5.

function App() {
  const [search, setSearch] = React.useState("Dehradun");
  const [searchHistory, setSearchHistory] = React.useState([]);

  const doSearch = () => {
    if (search.length > 0) {
      fetch(
        `https://api.openweathermap.org/data/2.5/weather?q=${search}&units=metric&appid=7938d9005e68d8b258a109c716436c91`
      )
        .then((res) => res.json())
        .then((result) => {
          setSearchHistory((prevState) => [
            [search, result],
            ...prevState.slice(0, 4)
          ]);
          setSearch("");
        });
    }
  };

  return (
    <div>
      <input onChange={(e) => setSearch(e.target.value)} value={search} />
      <button onClick={doSearch}>search</button>
      {searchHistory.map(([search, result], index) => (
        <div key={index}>
          <b>{search}</b> : {JSON.stringify(result)}
        </div>
      ))}
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></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