I am trying to save some data to my sql database from my app on button press by referencing the data from my store. but nothing gets added and I don't know why. I'm still learning sql. this is where I attempt saving data to database
onst {
userAddress,
userLongitude,
userLatitude,
destinationLatitude,
destinationAddress,
destinationLongitude,
} = useLocationStore();
const createData = async () => {
await fetchAPI('/(api)/data/create', {
method: "POST",
body: JSON.stringify({
origin_address: userAddress,
destination_address: destinationAddress,
origin_latitude: userLatitude,
origin_longitude: userLongitude,
destination_latitude: destinationLatitude,
destination_longitude: destinationLongitude,
user_id: userId,
})
})
console.log(time, userAddress)
}
and this is my api post request
import {neon} from "@neondatabase/serverless";
export async function POST(request: Request) {
try {
const body = await request.json();
const {
origin_address,
destination_address,
origin_latitude,
origin_longitude,
destination_latitude,
destination_longitude,
user_id,
} = body;
if (
!origin_address ||
!destination_address ||
!origin_latitude ||
!origin_longitude ||
!destination_latitude ||
!destination_longitude ||
!user_id
) {
return Response.json(
{error: "Missing required fields"},
{status: 400},
);
}
const sql = neon(`${process.env.DATABASE_URL}`)
const response = await sql`
INSERT INTO rides (
origin_address,
destination_address,
origin_latitude,
origin_longitude,
destination_latitude,
destination_longitude,
user_id
) VALUES (
${origin_address},
${destination_address},
${origin_latitude},
${origin_longitude},
${destination_latitude},
${destination_longitude},
${user_id}
)
RETURNING *;
`;
return Response.json({data: response[0]}, {status: 201});
} catch (error) {
console.error("Error inserting data into recent_rides:", error);
return Response.json({error: "Internal Server Error"}, {status: 500});
}
}
I have created the table in my server before running this code and I also added a console.log
in the button function to insure its being called and those items are not null
and all seems to check out fine. even in my terminal it shows that the create api is actually being called but when I check my table its still empty.