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

161
Visualizações
How can I use a useState variable inside uesEffect?

I am trying to access the useState variable query in my function inside useEffect. I get the error React Hook useEffect has a missing dependency: 'query'. Either include it or remove the dependency array.

I think the problem is that im setting the (useState) query variable when the user types in the search bar and then I am trying to access this new query variable in the useEffect hook.

I want to fetch the api after I join the api url and the contents of query but after setQuery is executed which is after the user types in the search bar. How can I do this?

Thanks Heres the code; notice the query variable.

import React, { useState, useEffect } from "react";
import Grid from '@mui/material/Grid';
import PaperCard from '../components/ResearchPaperCard';

const apiUrl = "http://127.0.0.1:8000/api/search/?search=";


function SearchedPapers(){

    const [query, setQuery] = useState("");
    const [apiData, setApiData] = useState([])

    useEffect(() => {
        const getFilteredItems = async (query) => {
             let response = await fetch(apiUrl+query);
             let papers = await response.json();
             setApiData(papers);
             if (!query) {
                return papers
            }
            return papers;
            
        
        }
    
        getFilteredItems(query);
      },[]);

    
    console.log(apiData)
    return (
        <div className='SearchedPapers'>
            <label>
                Search
            </label>
            <input type='text' onChange={e => setQuery(e.target.value)}/>
            <div>
                
                    {apiData.map((paper) => {
                        return (
                    <Grid key={paper.title}>
                        <PaperCard title={paper.title} abstract={paper.abstract}/>
                        </Grid>
                        )
                    })}
            </div>
                

        </div>
    )
                }

export default SearchedPapers;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Right now your useEffect is triggered each time your component mount so basically when someone reaches this screen. At this time your query state is empty.

Try adding this :

 useEffect(() => {
        const getFilteredItems = async (query) => {
             let response = await fetch(apiUrl+query);
             let papers = await response.json();
             setApiData(papers);
             if (!query) {
                return papers
            }
            return papers;
            
        
        }
    
        getFilteredItems(query);
      },[query]) - - - - > here

By doing so, your useEffect will be triggered only and each time your query state changes

about 4 years ago · Juan Pablo Isaza Relatório

0

You should either include query in your dependency array i.e., second argument of your UseEffect hook or either remove. When it's(array) empty useEffect will only render once i.e., when your page render for first time but when removed useEffect runs both after the first render and after every update. When specified like you put 'query' in dependency array it will only run whenever there is change in 'query' state.

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