useState does not update - Reactjs

Asked

Viewed 1,423 times

1

I’m starting in the world of Reactjs. I have a front that is consuming a tracking API, so it returns me an object with status, responseMessage and Object, an array of objects. I do the unstructuration of the request and it performs the print normally on the console. But the moment I try to change the state, it does not accuse any error but also does not change the state of the component.

  const dispatch = useDispatch();
  const [dados, setDados] = React.useState([]);

  React.useEffect(() => {
    async function loadData(){
      await dispatch(signInRequestMultiportal());
      const response = await apiMultiportal.request({
        url: 'posicoes/ultimaPosicao',
        method: 'post',
        headers: {
          token: store.getState().auth.tokenMultiportal,
        }
      });

      const { object } = response.data;
      console.log(object)
      setDados(object);
      console.log(dados);
    }
    loadData();
  }, [])
{
 "status": 'OK',
 "responseMessage": "Requisição concluida",
 "object": [{
 }]
}

Print of the object, the top is the console.log(object) the bottom the console.log(dados)

inserir a descrição da imagem aqui

  • if you are saying that you do not also change on the screen or only on the console.log? console.log(dados);?:

  • In the.log console the data appears, but in useState it does not

  • your Object ta coming anything, like an array with 0 positions! if you saw this?

  • In the console.log(object) all data appears, but in console.log(dados) simply appears a [ ]

  • if you are confusing the balls, the console.log(data) has no data yet it takes a while to update following the example below that I will create

  • It worked, thank you very much!

  • if you have been successful please tick as an answer to your question

Show 2 more comments

3 answers

2

The state variable needs to be monitored to have its changes and this is easily solved with the use of useEffect with a Paramento of array containing its variable to be monitored, a simple example:

function App() {
  const [data, setData] = React.useState([]);

  const loadData = () => {
    let item = [];
    for(let i = 0; i < 10; i++) {
      item.push(i);
    }
    setData(item);
  }

  React.useEffect(() => {
    loadData();
  }, []);

  React.useEffect(() => { // esse é responsável em pegar as alterações
    console.log(data);
  }, [data]); // pela configuração no `array` com o nome da variável

  return (
    <div>      
      <ul>
      {data.map((i,k) => (<li>{i}</li>))}
      </ul>
    </div>
  )
}
ReactDOM.render(<App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

the way you did as the change is not perceived because it is asynchronous and so I use the useEffect it is necessary

0

What is happening in this case is that when useEffect runs the status value of the date variable is the initial value, if you add the variable data in the dependency array the code will execute as you expect.

React.useEffect(function loadData(){....}, [data])

but the loadData() function will be executed twice what is not ideal. then you can separate the console.log() on another useEffect()

React.useEffect(()=>{console.log(data)}, [data])

0

Lucas, useEffects is quite interesting, but if you don’t put anything in the array of the second argument, it will run once, putting a property there, it will run every time you have a change in that variable.

const dispatch = useDispatch();
  const [dados, setDados] = React.useState([]);

  React.useEffect(() => {
    async function loadData(){
      await dispatch(signInRequestMultiportal());
      const response = await apiMultiportal.request({
        url: 'posicoes/ultimaPosicao',
        method: 'post',
        headers: {
          token: store.getState().auth.tokenMultiportal,
        }
      });

      const { object } = response.data;
      console.log(object)
      setDados(object);
      console.log(dados);
    }
    loadData();
  }, [dados]) // Apenas colocar a propriedade para ficar sendo observada

I made an example in Jsfiddle to better illustrate if there is still doubt.

https://jsfiddle.net/gabrielgstein/4hwvo0Lj/3/

Browser other questions tagged

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