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

162
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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