I am brand new to JS and react, so I might be way off with my attempts so far, and also, my code is full of console.log for debugging, but the problem I am having is:
I have a functional component with a changeHandler and submitHandler function within. changeHandler is triggered by a 'file' input while submitHandler is called on form submission. The submitHandler makes 2calls to 2 separate end-points via axios: 1st - to create a new record in a DB 2nd - adds a file to that same record.
I want to use the res.roundId from the first call as a dynamic variable in the 2nd axios.post request.
I update the state of the 'details' (roundId) on line 29 using: setDetails(prevDetails=>({ ...prevDetails, roundId:res.data.roundId }))
However, the roundId is not updated to the res.data.roundId and therefore I cannot destructure this for the 2nd axios call.
Any suggestions on how I might achieve this? Full code below:
const FileUpload = () => {
const [file, setFile]= useState(null)
const[details, setDetails] = useState({consent:false,
idConfirmed:false,
label:"",
roundId:""})
const changeHandler=(e)=>{
setFile(e.target.files[0]);
setDetails(prevDetails=>({
...prevDetails,
consent:true,
idConfirmed:true,
label:"test_Label"
}));
};
const handleSubmission=(e)=>{
e.preventDefault();
axios.post(process.env.REACT_APP_URL_NEW_ROUND, details)
.then(res=>{
console.log("Full Details: ", res)
console.log("roundId: ", res.data.roundId)
setDetails(prevDetails=>({
...prevDetails,
roundId:res.data.roundId
}))
console.log("line 31 Details: ", details)
})
console.log("roundId line 34: ", details.roundId )
//console.log("Details", details)
const data = new FormData();
data.append("file", file)
axios.post(process.env.REACT_APP_URL_All_ROUNDS/details.roundId/file/upload", data)
.then(res=>{
console.log("Data: ",res.data)
console.log("success")
})
.catch((e)=>{
console.log("Error", e)
})
};