2

I'm having a problem with my get request function using Axios. whenever its got called, the get function always runs twice. I don't know what the problem is here. I have tried removing React.Strictmode tag but nothing changed. I started to think the webpack dev server is the problem here. Here is my code :

  1. my get Request function :
export default async function useSendResquest(url, handler) {
  var Response;
  Response = await axios.get(url).then((response) => {
    return response.data;
  });
  return handler(Response);
}
  1. My UseEffect Call :
useEffect(() => {
  useSendResquest(
    "http://localhost:8080/api/control?name=rgbLed&status",
    (Response) => {
      setLightState(Response);
    }
  );
  console.log("hi");
}, []);
  1. Network activity :

enter image description here

  1. My Console Log : enter image description here

does anyone have any clue?

Thank you all

5
  • Are you sure setLightState does not say "Hi" too? Commented Jun 15, 2022 at 5:44
  • i double check and it was not Commented Jun 15, 2022 at 6:47
  • Not related to the question but try to avoid using var use let instead Commented Jun 15, 2022 at 7:11
  • Can you try replacing the var with let or even better const? It might be unrelated, above all it's a good practice, but I do have a sneaking suspicion given it exists in global scope the response actually gets instantiated twice, first as the global initialization of var and then whatever gets passed by the return of the axios call, hence causing component to re-mount with updated state and useEffect running twice. Commented Jun 15, 2022 at 7:13
  • @SamuelHulla it's kind of weird tho, though I have tried your solution, and nothing changed. And I even try to comment the useSendResquest, the result is still the same Commented Jun 15, 2022 at 8:53

1 Answer 1

1

I found the problem with why my app kept rerendering.it is because of my index.html template. The webpack compiler tried to add <script defer src="bundle.js"></script> twice, at the top of the HTML and at the bottom of it tool. After fixing this problem in the webpack config, everything ran as it should.

Sign up to request clarification or add additional context in comments.

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.