@@ -115,36 +115,48 @@ export const xmlReducer = createReducer(
115115 const variables = duplicateState . dataset ?. codeBook . dataDscr . var || [ ] ;
116116 let variableGroups =
117117 duplicateState . dataset ?. codeBook . dataDscr . varGrp || [ ] ;
118- if ( duplicateState . dataset && variables . length ) {
119- const variablesMatched : MatchVariables = matchVariableIDs (
120- importDdiData . codeBook . dataDscr . var ,
121- variables ,
122- ) ;
123- duplicateState . dataset . codeBook . dataDscr . var = createNewVariables (
118+
119+ // Validate imported DDI structure before accessing
120+ const importedVariables = importDdiData ?. codeBook ?. dataDscr ?. var ;
121+ if ( ! duplicateState . dataset || ! variables . length || ! importedVariables ) {
122+ return { ...duplicateState } ;
123+ }
124+
125+ // Normalize single-element to array for fast-xml-parser
126+ const importedVariablesArray = Array . isArray ( importedVariables )
127+ ? importedVariables
128+ : [ importedVariables ] ;
129+
130+ const variablesMatched : MatchVariables = matchVariableIDs (
131+ importedVariablesArray ,
132+ variables ,
133+ ) ;
134+ duplicateState . dataset . codeBook . dataDscr . var = createNewVariables (
135+ variablesMatched ,
136+ variables ,
137+ variableTemplate ,
138+ ) ;
139+ if ( variableTemplate . groups ) {
140+ const importedVariableGroups =
141+ importDdiData . codeBook . dataDscr . varGrp || [ ] ;
142+ variableGroups = updateGroups (
143+ Array . isArray ( importedVariableGroups )
144+ ? importedVariableGroups
145+ : [ importedVariableGroups ] ,
124146 variablesMatched ,
125- variables ,
126- variableTemplate ,
127147 ) ;
128- if ( variableTemplate . groups ) {
129- const importedVariableGroups = importDdiData . codeBook . dataDscr . varGrp
130- ? importDdiData . codeBook . dataDscr . varGrp
131- : [ ] ;
132- variableGroups = updateGroups (
133- Array . isArray ( importedVariableGroups )
134- ? importedVariableGroups
135- : [ importedVariableGroups ] ,
136- variablesMatched ,
137- ) ;
138- }
139- duplicateState . info
140- ? ( duplicateState . info . importedSuccess = true )
141- : {
142- siteURL : '' ,
143- fileID : '' ,
144- apiKey : '' ,
145- importedSuccess : true ,
146- } ;
148+ duplicateState . dataset . codeBook . dataDscr . varGrp = variableGroups ;
149+ }
150+
151+ if ( duplicateState . info ) {
152+ duplicateState . info . importedSuccess = true ;
153+ } else {
154+ duplicateState . info = {
155+ secureUploadUrl : null ,
156+ importedSuccess : true ,
157+ } ;
147158 }
159+
148160 return {
149161 ...duplicateState ,
150162 } ;
0 commit comments