0
Hello, I’m having an error in React.Js that I don’t understand in trying to consume data from an API I created myself. I created a loop so that I could get the json information and print my site.
Below the code followed by the error:
import React, {useState, useEffect} from 'react';
const Produtos = () => {
const [produtos, setProdutos] = useState([]);
useEffect(async() => {
const result = await fetch("http://localhost:8080/React3/fse/src/php/produtosapi.php");
setProdutos(await result.json());
}, [])
return (
<>
<div className="container-fluid">
<div className="row">
{
produtos.map(value => {
return (
<div className="col-lg-3">
<div key={value.id}>
<img src= {value.imagem} alt="a" width="120" height="120" />
<h5>{value.descricao}</h5>
<h5>R$:{value.preco}</h5>
<br />
</div>
</div>
)
})
}
</div>
</div>
</>
)
}
export default Produtos;
error: "Effect callbacks are synchronous to Prevent race conditions. put the async Function Inside:"
Why did you put
produtos
as a dependency onuseEffect
? And why are you wearing.then
withasync
andawait
?– Rafael Tavares
I thought it would look better the example, you can be combining the two without problems, every asynchronous function returns Promises. For products, when placed as a dependency, the Component is rendered every time you have an update in the state of products. @Rafaeltavares
– Maurício Silva
If you update the status within the
useEffect
, and the state is a dependency, you will be making an infinite loop. Besides, you don’t even need toasync
andawait
using thethen
the way it is in the code– Rafael Tavares
Beauty guy, but I did the test did not give endless loop, try also, in relation to
then
I know you don’t have to, but as I said I thought you’d be better off to exemplify, that’s all. hugs @Rafaeltavares– Maurício Silva
That’s right, you won’t go into an infinite loop if the API returns the same value, but you’ll be making an additional request.
– Rafael Tavares