-1

I am inserting an address into my SQL db and returning the id of that address once it's inserted. If it is already inserted I get the id of the address that has been inserted previously. For some reason, the function itself returns undefined when called but I get it to log the correct value to the console inside of the function itself. How do I get it to stop returning undefined?

the insertAddress function that is logging the correct data but returns undefined

    const insertAddress = async (address) => {
        let addressId = 0
        try {
            const results = await axios.post('/insert-address', {
                address: address
            });
            console.log(`address insert Id: ${JSON.stringify(results.data.insertId)}`);
            if (results.data.insertId === 0) {
                try {
                    const result = await axios.get(`/get-address-id?${objectToQueryString(address)}`)
                    console.log(`address Fetch Succeeded ${result.data[0].address_id}`);
                    addressId = result.data[0].address_id
                } catch (error) {
                    console.log("address Fetch Failed:", error);
                }
            } else {
                addressId = results.data.insertId
            }
        } catch (error) {
            console.log("Address Insert Failed:", error);
        }
        return addressId
    }

the file I'm trying to return the address id to

import React, { useState, useEffect, useRef } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import SMaV from '../utils/stringMainpulationAndValidation'
import useAddresses from '../utils/useAddresses'
import useUsers from '../utils/useUsers'

export default function SelectPlan() {
    const location = useLocation()
    const navigate = useNavigate()
    const [insertAddress, stripAddress] = useAddresses()
    const [insertUser] = useUsers()


    const [showData, setShowData] = useState(location.state.showData)
    const [user, setUser] = useState(location.state.user)
    const [addressId, setAddressId] = useState(null);

    useEffect(() => {

    }, []);

    const handleSubmit = async () => {
        //add plan to showData =================================================

        try {
            // Add address to database
            var mailing_address_id = await insertAddress(user.mailing_address)
                .then(() => {
                    console.log(`insert address returned ${mailing_address_id}`)
                    // Update user with address id
                    setUser(prevState => ({ ...prevState, mailing_address_id: mailing_address_id }))
                })

            // Remove address attribute from user
            const { mailing_address, ...strippedUser } = user

            // Add user to database
            const user_id = await insertUser(strippedUser)
                .then(() => {
                    // update show primary user id
                    setShowData(prevState => ({ ...prevState, show_primary_user_id: user_id }));
                })
        } catch (error) {
            console.error(error)
        }

        console.log(`user mailing address id ${user.mailing_address_id}`)
        if (user.mailing_address_id === undefined) {
            setUser(prevState => ({ ...prevState, mailing_address_id }))
        }
        console.log(`try again user mailing address id ${user.mailing_address_id}`)

        console.log('submitted')

        return (
            <>
                <p>
                    user id {user_id}
                </p>
                <p>
                    user address id {user.mailing_address_id ? user.mailing_address_id : 'Loading...'}
                </p>
                <p>Select Plan</p>
                <button onClick={handleSubmit}>
                    Add Addresses & User
                </button>
            </>
        )
    }
}

the console log after the function is called

Ive tried taking the insert address call out of the handle submit function to give it more time to run but the await statementr should be holdin ght eother code until its finished. Ive tried puting the return statements in the insertAddress function inside of the try block and outside of the try blocks. Nothing I'm doing seeems to be returning the information I need when I need it.

RLee
  • 1

1 Answers1

0

The function is fine, it's this part which doesn't return anything:

var mailing_address_id = await insertAddress(user.mailing_address).then(() => {
  console.log(`insert address returned ${mailing_address_id}`);
  // Update user with address id
  setUser((prevState) => ({
    ...prevState,
    mailing_address_id: mailing_address_id,
    // missing return here
  }));
});

Either use then correctly:

await insertAddress(user.mailing_address).then((mailing_address_id) => {
  console.log(`insert address returned ${mailing_address_id}`);
  // Update user with address id
  setUser((prevState) => ({
    ...prevState,
    mailing_address_id: mailing_address_id,
  }));
});

Or just use await because you are already using it:

var mailing_address_id = await insertAddress(user.mailing_address);
console.log(`insert address returned ${mailing_address_id}`);
// Update user with address id
setUser((prevState) => ({
  ...prevState,
  mailing_address_id: mailing_address_id,
}));

Or do both but with return:

var mailing_address_id = await insertAddress(user.mailing_address).then((mailing_address_id) => {
  console.log(`insert address returned ${mailing_address_id}`);
  // Update user with address id
  setUser((prevState) => ({
    ...prevState,
    mailing_address_id: mailing_address_id,
    return mailing_address_id
  }));
});
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • Thank you, I jumped into callbacks without fully understanding them. I've switched it to get rid of the then() call. It works. The state object won't update afterward but you have solved my issue with this question. Thank you. – RLee Mar 14 '23 at 09:51
  • The state object won't update immediately, see https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately – Konrad Mar 14 '23 at 11:20