@ -9,10 +9,10 @@ import trim from 'lodash/trim'
import { formIds } from 'config/form'
import type { UserInfo } from 'requests/saveUserInfo'
import { getUserInfo } from 'requests/getUserInfo'
import { saveUserInfo } from 'requests/saveUserInfo'
import { City , getCountryCities } from 'requests/getCountryCities'
import type { SelectedCountry } from './useCountries'
import { useUserInfoForm } from './useUserInfoForm'
import { useValidateForm } from './useValidateForm'
@ -37,7 +37,6 @@ export const useUserInfo = () => {
updateFormError ,
updateFormValue ,
} = useUserInfoForm ( )
const readTrimmedValue = useCallback (
( fieldName : string ) = > trim ( readFormValue ( fieldName ) ) || null ,
[ readFormValue ] ,
@ -54,8 +53,7 @@ export const useUserInfo = () => {
const address_line2 = readTrimmedValue ( formIds . address2 )
const city = readTrimmedValue ( formIds . city )
const countryId = Number ( readTrimmedValue ( formIds . countryId ) )
saveUserInfo ( {
const newUserInfo = {
address_line1 ,
address_line2 ,
city ,
@ -67,7 +65,14 @@ export const useUserInfo = () => {
phone ,
postalCode ,
region ,
} ) . then ( ( ) = > saveButton ? . current ? . blur ( ) )
}
const newUserInfoForStorage = {
. . . newUserInfo ,
country : JSON.parse ( localStorage . getItem ( 'initCountry' ) as string ) ,
}
localStorage . setItem ( 'init' , JSON . stringify ( newUserInfoForStorage ) )
localStorage . setItem ( 'disabled' , 'true' )
saveUserInfo ( newUserInfo ) . then ( ( ) = > saveButton ? . current ? . blur ( ) )
}
} , [
readTrimmedValue ,
@ -76,14 +81,30 @@ export const useUserInfo = () => {
] )
useEffect ( ( ) = > {
getUserInfo ( ) . then ( ( res : UserInfo ) = > {
forEach ( res , ( value : string | number | SelectedCountry , key : string ) = > {
if ( value && typeof value === 'object' ) {
onCountrySelect ( value , false )
} else if ( value ) {
updateFormValue ( key ) ( String ( value ) )
}
} )
getUserInfo ( ) . then ( ( res : any ) = > {
const response = res
const convertResponse = ( ) = > {
forEach ( response , ( value : string | number | SelectedCountry , key : string ) = > {
if ( value && typeof value === 'object' ) {
onCountrySelect ( value , false )
} else if ( value ) {
updateFormValue ( key ) ( String ( value ) )
}
} )
}
if ( response . city === null && response . city_id !== null ) {
getCountryCities ( '' , response . country . id ) . then ( ( resp ) = > {
const initCity = resp . find ( ( i :City ) = > i . id . toString ( ) === response . city_id . toString ( ) )
if ( initCity !== undefined ) {
response . city = initCity . name
localStorage . setItem ( 'init' , JSON . stringify ( res ) )
convertResponse ( )
}
} )
return
}
localStorage . setItem ( 'init' , JSON . stringify ( response ) )
convertResponse ( )
} )
} , [ updateFormValue , onCountrySelect ] )