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