11

While I fetch data from API and set the response to a array using useEffect it call the API repeat continuous.

let [product, setproduct] = useState([]);

async function fetchData() {
    let response = await axios(
      `api`
    );
    let user = await response.data;
    setproduct(user);
    console.log(product);
  }

  useEffect(() => {
    fetchData();
  }); 

4 Answers 4

9

From the docs,

Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update. (We will later talk about how to customize this.) Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.

You can provide the empty dependency array / [] as second argument to useEffect, it is same as componentDidMount which will executes only once in component life cycle.

useEffect(() => {
    fetchData();
}, []); //This will run only once 
Sign up to request clarification or add additional context in comments.

Comments

2

Pass empty [] as an second argument to useEffect method. It will be called on initial render, like below.

  useEffect(() => {
    fetchData();
  }, []); 

Comments

1
let [product, setProduct] = useState([]);

// This function will be only called once
async function fetchData() {
    let response = await axios("api");
    let user = response.data;// Don't need await here
    setProduct(user);
    console.log(product);
}

useEffect(() => {
    fetchData();
}, []); 

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

i think the blow example will help you through fetch API .

import React , {useEffect} from "react";
import axios from "axios";

const Courses = ()=>{

    useEffect(()=>{
        getProducts()
    })




    const getProducts = async() => {
        await axios.get('api/get_all_products')
        .then(({data}) =>{
            console.log("this is data from api ");
            console.log('data' , data);

        } )

        console.log("data ehre ");
    }


    return(
        <div>
            <h2>Products data  here</h2>

        </div>

    )
};

export default Courses;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.