Home > Blockchain >  too many request on react using axios on get api
too many request on react using axios on get api

Time:02-15

export async function onGetNews(){
    let data = await axios.get(`${Link}/news`, {
        params: {
            limit: 1
        }
    }).then(res => {
        return (res.data)
    });
    return data
}

I tried a lot of solutions and I didn't find a good one. I use limit and other ... and when I use useEffect with export function it gives me an error

export  function OnGetServices(){
     
    const [service, setService] = useState([])

    useEffect(() => {
        setTimeout(async () => {
            let data = await axios.get(`${Link}/services`, {}).then(res => {
                setService(res.data)
            });
        }, 1000);
        console.log(data);
    }, []);

    console.log(service);
    return service;
}

CodePudding user response:

Why are you doing .then() when you are using async/await? Try this:

export async function onGetNews(){
  let  res= await axios.get(`${Link}/news`, {
    params: {
      limit: 1
    }
  });
  return res.data
}

And your react snippet can be:

export  function OnGetServices(){
  const [service, setService] = useState([])

  useEffect(() => {
    setTimeout(async () => {
      let res = await axios.get(`${Link}/services`, {})
      setService(res.data);
      console.log(res.data);
    }, 1000);
  }, []);
}

And if you don't really need the setTimeout, you could change the implementation to:

export  function OnGetServices(){
  const [service, setService] = useState([])

  useEffect(() => {
    const fn = async () => {
      let res = await axios.get(`${Link}/services`, {})
      setService(res.data);
      console.log(res.data);
    }
    fn();
  }, []);
}

CodePudding user response:

Async/await drives me crazy either. I wrote a solution, but I'm not sure if it performs good practices. Feedback appreciated.

https://codesandbox.io/s/react-boilerplate-forked-y89eb?file=/src/index.js

CodePudding user response:

If it's a hook then it has to start with the "use" word. Only in a hook, or in a Component, you can use hooks such as useEffect, useState, useMemo.

export  function useService(){ //notice the "use" word here
     
    const [service, setService] = useState([])

    useEffect(() => {
        setTimeout(async () => {
            let data = await axios.get(`${Link}/services`, {}).then(res => {
                setService(res.data)
            });
        }, 1000);
        console.log(data);
    }, []);

    console.log(service);
    return service;
}


const SomeComponent = () => {
      const service = useService();


}
  • Related