Navigate to the recently added entry using Router.push in your NextJS/Supabase project, leading to no return value

In the process of developing an application that allows users to register shipments between different locations, I encountered a roadblock. Once a user creates a new shipment and saves it, they should be able to add goods to it. However, despite my efforts to structure the system in such a way that upon submitting the data to Supabase, it should return the ID which would then be used to route to the next page via Router.push, the routing does not seem to be working as expected.

Below is the code snippet for the handleSubmit function:

const router = useRouter()
const [id2, setId] = useState('')

const handleSubmit = async (e) => {
        e.preventDefault()

        if (!location_to_city || !location_to_country || !location_from_city || !location_from_country) {
            setFormError('Please fill in all the fields correctly')
            return
        }

        const { data, error } = await supabase
            .from('shipment')
            .insert([{ location_from_address_1, location_from_zipcode, location_from_city, location_from_country, location_to_address_1, location_to_zipcode, location_to_city, location_to_country, customs, excise, dangerous_goods, documents, documents_information, user_id: user.id }])
            .select()

        console.log(data)
        setId(data.id)
        console.log(id2)

        if (error) {
            console.log(error)
            setFormError('Please fill in all the fields correctly')
        }

        if (data) {
            setFormError(null)
            
        }

        router.push('/shipments/' + id2)
    }

Upon entering this data, the console displays the following information:

active
: 
true
created_at
: 
"2022-12-23T10:40:13.783891+00:00"
customs
: 
false
dangerous_goods
: 
false
documents
: 
false
documents_information
: 
""
excise
: 
false
id
: 
81
location_from_address_1
: 
""
location_from_city
: 
"a"
location_from_country
: 
"b"
location_from_zipcode
: 
""
location_to_address_1
: 
""
location_to_city
: 
"c"
location_to_country
: 
"d"
location_to_zipcode
: 
""
user_id
: 
"00063c91-f745-4a74-ba86-90603b84bed5"

However, despite obtaining the correct ID from the data, the URL does not reflect this when trying to route to the next page - it remains as "http://localhost:3000/shipments/". If anyone has any insights on how to successfully include the ID value in the url used by router.push, I would greatly appreciate your help!

Answer №1

Here is my solution:

To access the response of the Supabase .select() function, we can retrieve it from the first object in the data array. Therefore, the correct usage would be:

router.push(`shipments/` + data[0].id)

Answer №2

Since id2 remains equal to '' in this particular render, it will be altered in the upcoming one.

Instead of using direct manipulation, you have the option to push like so:

router.push('/shipments/' + data[0].id)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering issues while creating a basic digital clock webpage using React

I am trying to create a simple clock in React, but I want all the time data to be stored in a single object instead of separate states for hours, minutes, and seconds. However, I keep running into an error. Can someone please assist me? import React from & ...

Refreshing dynamically added rows through ajax updates

I'm struggling to clearly articulate my problem. Currently, I have a function that retrieves values from a database using ajax and then dynamically adds each result as a row in a table. This allows users to edit or delete any row as needed. I'm ...

Implement a jQuery click event on a dynamically generated button in the code-behind

A button (Replybtn) is dynamically created when clicked in the code-behind file. --Default.aspx.cs-- protected void ReloadThePanelDetails_Click(object sender, EventArgs e) { litResultDetails.Text = litResultDetails.Text + "<button id='Replyb ...

Animation not fluid with ReactCSSTransitionGroup

Currently, I am in the process of developing an image carousel that showcases images moving smoothly from right to left. However, despite its functionality, there seems to be a slight jaggedness in the animation that I can't seem to resolve. Interesti ...

What causes the variance in AJAX errors between IE and Chrome browsers?

Consider the code example provided below: <script> function xyz() { $.ajax({ type: "GET", url: "https://zx/xyz/uvw", timeout: 6000, dataType: "jsonp", ...

I'm having trouble launching Clinic.js, any suggestions on what steps I should take next?

When starting up your application, use the following command: clinic doctor --on-port 'autocannon -m POST localhost:8000/users/register' -- node dist/main.js If you need help, check out the Clinic.js Doctor - v9.2.0 log. The clinic doctor tool ...

What is the best way to save a scheduled cron reference in a database in order to deactivate it at a later time in a

I have implemented a system using cron to schedule push notifications. The user provides the push notification data and the scheduled time, and I use cron to send the notifications at the specified time. Below is the code snippet showing how I create a cr ...

Tips for patiently waiting for a promise to be fulfilled

Currently, I am faced with a scenario in a NodeJs framework where a specific function must be synchronous, yet I need to access a value asynchronously. Ideally, I would be able to return a promise, however, that is not feasible. To address this issue quic ...

Using MongoDB to group by the difference in dates and retrieve the hour value

Currently, I am working on an application and I require some information from my database: I have a model called "traitement" which includes a user, The "traitement" model has a start date and an end date, both in Date format, allowing MongoDB to use ISO ...

What is the best way to populate nested elements with jQuery?

I am trying to showcase the latest NEWS headlines on my website by populating them using Jquery. Despite writing the necessary code, I am facing an issue where nothing appears on the webpage. Below is the HTML code snippet: <div class="col-md-4"> ...

Creating dynamic dropdown menus within a Rails 3 form using Prototype and incorporating database queries

Recently, I've been on the hunt for a seamless method to create dynamic dropdown menus within a form that can be populated with data from a database based on the selection of a previous dropdown. Unfortunately, my search for a suitable Rails 3/prototy ...

There is an excessive amount of recursion happening in angular.js when it comes to

I've been troubleshooting a recursion error in my angular.js web application. The error message listed below keeps popping up multiple times (twice per second) in the console whenever the issue occurs. Since the log statements only point to errors in ...

JavaScript: Break apart and tally the number of words within a given string

If I have an input string with the value "testing the string", I want to create a function that splits each word and counts how many times each word appears in the input string. The desired output should look like this: testing: 1, the: 1, string: 1 Than ...

Eliminate HTML tags and formatting, but retain the anchor tags within the string

I have a string variable with HTML content that I need to clean up by removing all tags and formatting, while still preserving anchor tags for clickable links. content = "<div><a href=\"1\">I</a> was going here and then <a h ...

Next.js: The file instrumentation.ts does not execute on the server side

On app launch, I need to execute some server-side code for initialization in my next.js app. I came across the instrumentation feature, which seemed like a good fit for my requirement. However, I encountered an error when trying to access node.js librarie ...

ng-class: Issue detected - The symbol '-' is positioned at column {2}

I'm having an issue with ng-class. I need to add a disabled state class if the role has admin privileges, but I keep getting an error. Here is the HTML: <label class="toggle modal-label-box" ng-class="{state-disabled: checkCanModify()}"> &l ...

React - Issue with Input event handling when utilizing both onChange and onKeyDown functions

I was attempting to create a feature similar to a multi-select, where users could either choose a value from a list or enter a new value. The selected value should be added to an array when the user presses the enter key. To monitor changes in the input ...

Utilize SCSS values within TypeScript by applying them on a class level

let changeClassDisplay = document.getElementsByClassName('sidebar'); for (var i = 0; i < changeClassDisplay.length; i += 1) { changeClassDisplay[i].style.display = 'block'; } I encountered an issue with this code whe ...

``There seems to be an issue with JQuery.Ajax not properly displaying on Samsung Smart

I attempted to use JQuery.Ajax to interact with my webservice Below is the code snippet: Main.onLoad = function() { // Enable key event processing this.enableKeys(); widgetAPI.sendReadyEvent(); //$("#h2Test").html("Change On Text"); ...

Move information from one page to another

I'm currently using Ionic 2 and attempting to pass data from one page to another. Specifically, I want to transfer the data of a selected list item from the first page (quickSearch) to the second page (quickSearchDetail). To illustrate this, refer to ...