1
I’m using the useEffect to get the data from a table. The problem is that even if I receive the data from the api, the states are not updated in the first iteration, so I have to do two get in the api every time I change a page or apply a filter. Is there anything you can do that will cause the states to be updated in the first iteration?
useEffect(() => {
async function getData(){
try {
const response = await axios.get(url, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': "Bearer " + localStorage.getItem('user_token')
}
});
console.log(response);
setNextPage(response.data.next);
setPrevPage(response.data.previous)
setPageResults(response.data.results);
setCount(response.data.count);
setMount(0);
console.log(pageResults);
} catch (error) {
console.log('Erro:', error);
}
}
getData();
}, [mount]);
First iteration:
Second iteration:
useStates used as request in the comments below:
const [url, setUrl] = useState(defaultUrl);
const [mount, setMount] = useState(1);
const [count, setCount] = useState(0);
const [page, setPage] = useState(0);
const [nameSearch, setNameSearch]= useState("");
const [citySearch, setCitySearch] = useState("");
const [stateSearch, setStateSearch] = useState("");
const [minAgeSearch, setMinAgeSearch] = useState(0);
const [maxAgeSearch, setMaxAgeSearch] = useState(100);
const [rowsPerPage, setRowsPerPage] = useState(20);
const [nextPage, setNextPage] = useState("");
const [prevPage, setPrevPage] = useState("");
const [pageResults, setPageResults]= useState([]);
Have you tried removing the mount from the second useEffect argument? And also put the useState that you are creating.
– Bruno Elias de Souza
already, it becomes an infinite loop. Also, it continues to update the state only in the second iteration. As for useState, I made an issue by question, adding them.
– Bruno Santa Cruz