The process of merging these two functions involves ensuring that one function does not start until the other has successfully completed its task

A closer look at the two functions in question:

   const handleSubmit = async (e) => {

    e.preventDefault();
    console.log(songLink)
    const newSong = {
        songName,
        songLink,
        userId
    };
    const song = await dispatch(postSong(newSong))
        .catch(async (res) => {
            const data = await res.json()
            if (data && data.errors) setErrors(data.errors)
        })
    reset();
};

const uploadSong = (files) => {
    console.log(files[0])
    const formData = new FormData()
    formData.append('file', songSelected)
    formData.append('upload_preset', 'd3gthd7l')
    Axios.post("https://api.cloudinary.com/v1_1/dyhfkvy6u/video/upload", formData).then((response) => {
        console.log(response.data.url, 'responseeee')
        setSongLink(response.data.url)
    })
}

The primary challenge lies in completing the upload process within the uploadSong function to retrieve response.data.url and store it for later use in handling the submit process while creating a new song. I'm uncertain whether this issue stems from a small oversight or a lack of understanding regarding a crucial concept. Is there a need to return the URL and then await the function?

Displayed below is the complete file:

import { useState } from "react";
import { useDispatch } from "react-redux";

import { postSong } from "../../store/song";

import { useSelector } from "react-redux";

import Axios from 'axios'

const SongForm = () => {
    const dispatch = ...

    // Remaining content will be similar but slightly modified to ensure uniqueness.

Answer №1

Your form seems to have both an onSubmit handler and an onClick action for its submit button. This means that two actions will be triggered when the submit button is clicked.

To avoid this, consider removing either the onClick from the button or the onSubmit from the form so that only one action is executed.

If you choose to keep the onSubmit as the desired action, make sure to call both functions within that function. If the first function (upload) is asynchronous, remember to await its result before proceeding with the next function.

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

Dividing an AngularJS module across multiple iFrames on a single webpage

Currently, I am working on a web application that consists of 1 module, 5 pages, and 5 controllers. Each HTML page declares the same ng-app. These pages are loaded within widgets on a web portal, meaning each page is loaded within an iFrame in the portal. ...

Tips for resolving issues related to Nodemailer configuration

I am currently working on a script that sends form data to an email address. I am using Express and Nodemailer with Node.js, but as a beginner, I am struggling to understand why the email authorization stops and prevents the letters from being sent. Here ...

Is there a way to redirect the user directly to the upload page without displaying the response?

Recently, I came across this code snippet that adds a progress bar to an upload form. Currently, the code displays the response from the upload page below the form. However, my goal is to redirect the user to the upload page so they can view the response t ...

What is the process by which a web browser executes a ".jsx" file while in development?

As a beginner in the world of react, I have successfully been able to execute the dev and build tests. One question that has been boggling my mind is how browsers handle ".js" files. I know that when a project is build, the browser runs the &quo ...

The Mongoose function findbyIdAndRemove is currently not working properly when triggered on the client-side

I have a specific route in my app that uses the mongoose method findByIdAndRemove. Strangely, when I test this route using postman, it successfully deletes documents from my database. However, when I try to call this method from my client-side JavaScript f ...

Troubleshooting a Vue 2 component's prop receiving an incorrect value

I'm currently working on creating a menu that navigates between categories. When a category has a sub-category, it should return a boolean value indicating whether it has a sub-category or not. <template> <select><slot></slot ...

What is the procedure to obtain a session object on the server side in next.js version 14?

I am currently utilizing version 14 of next.js with its app routing feature and NextAuth. My goal is to secure the API, however, I encounter a null object when using the getServerSession( authOptions ) method while attempting to access a protected endpoin ...

React with REDUX is refreshing the entire state following the update action

For the past day, I've been working on resolving a bug that has been plaguing me. Everything was functioning perfectly before the update action. I made sure to log all the states before executing the update action. However, after creating a model, t ...

Encountering an issue with React router that reads: "TypeError: type.toUpperCase is not a function."

I'm currently working on building an isomorphic app that utilizes react and express.js. For client-side routing, I am using React Router. However, during the app's runtime, I encountered several errors and warnings in the console: Warning: Faile ...

Add a container element resembling a div inside a table without implementing the table layout

I am working with a table that is rendered by DataTable, and I have the requirement to dynamically append new elements inside the table like this: The dark grey area represents the new DOM elements that need to be inserted dynamically. The first row cont ...

I am currently attempting to create a JavaScript function that searches for the <td> elements within an HTML table. However, the function fails to work properly when there are <th></th> tags included

UPDATE: Scratch that, I managed to solve my issue by creating a separate table for the header to contain all of my <th> tags I am working with an HTML table and I would like to add a search bar to filter through the content since it is quite large. ...

Can someone assist me in choosing a specific button from a group of buttons within material ui?

I have a situation where I have an array of phone numbers, each one with a button to copy the number and initiate a call. The challenge is that we are using material-ui v4 for our UI components. What I would like to achieve is that when someone clicks on ...

What steps can be taken to eliminate a npm install error?

I have been attempting to execute the following project: https://github.com/kentcdodds/react-in-angular This repository serves as an illustration of incorporating React into AngularJS. It consists of three tags that demonstrate the process of transitio ...

Is there a way to filter out only the objects from the JSON data and exclude the strings?

I am facing an issue while looping through a JSON object. The presence of strings in the JSON is causing the loop to fail. How can I iterate only through the objects in the JSON without affecting the loop? My main goal is to iterate through the objects co ...

Creating a worldwide entity through the use of an Immediately Invoked Function Expression

There are 2 methods I discovered for defining a global object using IIFE: (function () { var func = function () { }; window.func = func; }()); compared to: (function (myFunc) { window.func = myFunc(); }(function () { var func = functi ...

Webpack encountered an error: SyntaxError due to an unexpected token {

I recently implemented Webpack for my Django and Vue project, but I encountered an error when trying to run webpack. Can anyone help me troubleshoot this issue? $ node --use_strict ./node_modules/.bin/webpack --config webpack.config.js node_modules/webp ...

Retrieve the Gatsby Component in a function

I've been trying to access a Gatsby component called Anime from outside of it, but I'm struggling to determine its instance name. Here's the code snippet: import React from 'react' import PropTypes from 'prop-types&ap ...

Unable to retrieve real-time data from Firestore using getStaticPaths in Next.js

While fetching data from Firebase Firestore using getStaticProps is successful, I encounter a 404 page when attempting to implement the logic for retrieving details of individual items with getStaticPaths. The current state of my [id].js code appears as fo ...

I'm noticing that when I refresh the page, my inputs seem to disappear from the page, yet I can see that they are saved in the console's local

If anyone can help me with this issue I'm facing, I would greatly appreciate it. My aim is to retain values in the text box along with local storage even after refreshing the page. Here is an example of the code I am working with: Link to my web appl ...

Encountered a Next-Auth Error: Unable to fetch data, TypeError: fetch failed within

I've been struggling with a unique issue that I haven't found a solution for in any other forum. My Configuration NextJS: v13.0.3 NextAuth: v4.16.4 npm: v8.19.2 node: v18.12.1 When the Issue Arises This particular error only occurs in the pr ...