Home > Software engineering >  How to get data from an API only once when the page is loaded using axios.get method?
How to get data from an API only once when the page is loaded using axios.get method?

Time:12-12

I am a beginner in React, I want to get the data from my API only once when the particular page is loaded and save it to a variable i.e. "todo". I can see in my backend code that this code is sending continuous request to the api.

const [todo, setTodo] = useState({})
        const fetchdata = async () => {
            const res = await axios.get(`http://localhost:8000/api/get-todo/${nid}`);
            setTodo(res.data);
        };
        useEffect(() => {
            fetchdata();
        },)

CodePudding user response:

You need to use square brackets ([]) at the end of the useEffect hook to make the send request one time.

useEffect(() => {
    fetchdata();
}, [])
  • Related