I'm new to Stack Overflow and seeking help with a specific issue on my Rails backend and Vue.js frontend website.
The challenge I'm facing involves making two POST requests simultaneously when the submit button is clicked. My "Trips" controller and "User_Trips" controller are crucial for creating and linking trips in my database. For a newly created trip to display properly, a corresponding user_trip must also be generated.
Although my trip post works seamlessly, the user_trip post encounters obstacles. I believe the issue lies in passing the recently created trip's id as a parameter needed for creating a user_trip. Here's an excerpt of the code snippet from Vue.js that I'm grappling with:
<script>
import axios from "axios";
export default {
data: function() {
return {
trips: [],
errors: [],
name: "",
country: "",
state: "",
city: "",
postal_code: "",
start_date: "",
end_date: "",
image: "",
trip: this.trip
};
},
mounted: function() {
// axios.get("http://localhost:3000/api/trips").then(
// function(response) {
// console.log(response);
// this.trips = response.data.trips;
// }.bind(this)
// );
},
methods: {
submit: function() {
var params = {
name: this.name,
country: this.country,
state: this.state,
city: this.city,
postal_code: this.postal_code,
start_date: this.start_date,
end_date: this.end_date,
image: this.image
};
axios
.post("http://localhost:3000/api/trips", params)
.then(response => {
axios.get("http://localhost:3000/api/trips").then(
function(response) {
console.log(response);
this.trips = response.data.trips;
}.bind(this)
);
})
.catch(error => {
this.errors = error.response.data.errors;
});
var paramsTwo = {
trip_id: this.trip.id
};
axios
.post("http://localhost:3000/api/usertrips", paramsTwo)
.then(response => {
this.$router.go("/home");
})
.catch(error => {
this.errors = error.response.data.errors;
});
}
}
};
</script>
The error message displayed in the console log is: Uncaught TypeError: Cannot read property 'id' of undefined. This leads me to suspect that I might not be selecting the correct trip from the array. However, upon reviewing the GET request in the log, the newly created trip doesn't appear - only in the database. Any useful suggestions would be greatly appreciated! - Thanks