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

Viewed 985

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();
        },)
1 Answers

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

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