I have the problem with axios.post in my app. It sends two times the same request with the same body. I have tried to google the problem, but find nothing. How can I fix it?
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;
CodePudding user response:
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.
CodePudding user response:
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.