0

I have a problem with axios.post sending two times the same request with the same body. I have tried to Google the problem but find nothing. How can I fix it?

requests

App.js

import logo from './logo.svg';
import './App.css';
import Register from "./register";
import SendToken from "./sendToken";
import {BrowserRouter, Routes, Route} from "react-router-dom";
import Confirmation from "./Confirmation";

import {useParams} from "react-router-dom";

function App() {
  return (
      <BrowserRouter>
          <div>
              <Routes>
                  <Route path="/registration" element={<Register/>}/>
                  <Route path="/confirmation" element={<Confirmation/>}/>
                  <Route path="/account/registrationConfirm/:data" element={<SendToken/>}/>
              </Routes>
          </div>
      </BrowserRouter>

  );
}

export default App;

sendToken.js

import axios from 'axios';

const SendToken = () => {
    let parts = window.location.href.split('/');
    let length = parts.length;
    let token = parts[length - 1] == '' ? parts[length - 2] : parts[length - 1]

    axios.post("http://localhost:8080/api/v1/registration/registrationConfirm", {token}).then((data) => {
        console.log(data.status)
        console.log(data.data)
        console.log(token);
        }
    }).catch(() => {
        alert("An error occurred on the server")
    })

    return (
        <div>
            Token send
        </div>
    )
}

export default SendToken;
DᴀʀᴛʜVᴀᴅᴇʀ
  • 5,839
  • 15
  • 57
  • 101
TomLott
  • 31
  • 4

2 Answers2

4

when you use to send request like this everytime that page rerenders it sends the request try using useEffect:

useEffect(() => {
    axios
    .post("http://localhost:8080/api/v1/registration/registrationConfirm", {token})
    .then((data) => {
        console.log(data.status)
        console.log(data.data)
        console.log(token);
    })
    .catch(() => {
        alert("An error occurred on the server")
    })
},[]}

the second parameter tells you that this code will run only one time.

Anurag Srivastava
  • 13,226
  • 4
  • 25
  • 40
Ali Navidi
  • 349
  • 1
  • 10
1

You might need to use useEffect() with a second argument as an empty array in your SendToken component.

import {useEffect} from "react";

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

To make sure that it runs only once.