useEffect not updating states in the first iteration

Asked

Viewed 718 times

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:

Primeira iteração

Second iteration:

Segunda iteração

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.

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

1 answer

0


Needs to be put on useEffect one array without any item, ie, [], and this has the effect at the moment the component is created the method is invoked(componentDidMount() if class), example of code working:

function Root() {
  const [obj, setObj] = React.useState([]);
  function getDataAsync() {
      const url = 'https://randomuser.me/api/?results=100';
      fetch(url)
        .then(response => response.json())
        .then(response => {        
          setObj(response.results);
        })
  }
  React.useEffect(() => {
    getDataAsync();
  }, []); 
  if (obj.length === 0) {
    return <h4>{'Carregando ...'}</h4>;
  } else {
    return (
      <ul>
        {
          obj.map(item => (
            <li key={item.login.uuid}>
              {item.login.username}
            </li>
          ))
        }
      </ul>
    )  
 }
}
ReactDOM.render(<Root/> , document.getElementById('root'));
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root">Aguarde ...</div>

I prefer to create the method always outside and call inside the useEffect, but, if created inside also works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.