React-Hooks/exhaustive-deps | Error in an assync function when taking data from an API

Asked

Viewed 71 times

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:"

1 answer

2


Talk man, so you can’t be using the async within the useEffect you should call a function to run inside it and then call it, I made an example of how you can is solving your problem:

import React, {useState, useEffect} from 'react';


const Produtos = () => {
    const [produtos, setProdutos] = useState([]);

  useEffect(() => {
    async function getProducts(){
      await fetch("http://localhost:8080/React3/fse/src/php/produtosapi.php")
        .then((response) => {
          return response.json();
        })
        .then((data) => {
          setProdutos([data]);
        });
    }
        
     getProducts();
        
    }, [produtos]);

    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;

  • Why did you put produtos as a dependency on useEffect? And why are you wearing .then with async and await?

  • 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

  • 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 to async and await using the then the way it is in the code

  • 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

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

Browser other questions tagged

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