benwinding / react-admin-import-csv

A csv file import button for react-admin
https://benwinding.github.io/react-admin-import-csv
MIT License
135 stars 46 forks source link

array of one element #57

Closed shrue348 closed 3 years ago

shrue348 commented 3 years ago

I transform some data width transform func in parse config to array of numbers (for example [123,123,123,123]) If array has 2 and more elements, it transmitted to dataProvider normally But if array has one element (for example [123]), in transmitted to dataProvider as single number 123

benwinding commented 3 years ago

Hi @shrue348, Thanks for checking out the library, but I'm having a little trouble understanding the problem. Are you saying that you're storing an array in a CSV field?

Please try the following to help me understand your issue:

Cheers, Ben

shrue348 commented 3 years ago

ok here is my config

const regExp = /[([^)]+)]/; export const importCSVConfig = { parseConfig: { dynamicTyping: true, transform: (val: any) => { if (val.match(regExp)) { return (val.match(regExp)[1] || '') .split(',') .map((el: any) => ( Number(el) ? Number(el) : el )); } return val; }, }, preCommitCallback: (action: 'create' | 'overwrite', values: any) => values.map((item: {[key: string]: any}) => { const newItem = {} as {[key: string]: any}; Object.keys(item).forEach((key: string) => { if ( item[key] !== null && item[key] !== 'undefined' ) newItem[key] = item[key]; }); return newItem; }), };

in transform function i check field on array, cut string from [], split it for real array, and try convert array items to numbers in preCommitCallback I push real fields (not null and undefined in payload object to dataProvider) if array from transform func has 2 or more elements this field come in values of preCommitCallback as array BUT! if array has one element (for exaple [123]), it come in values as simple number or string

csv id, somefield 10, [1,2,3,4,5] payload {id: 10, somefield: [1,2,3,4,5]}

csv id, somefield 10, [12345] payload {id: 10, somefield: 12345 /* not[12345] */}

PS i dont find in documentation, how to import to mysql json fields arrays or objects (i need arrays) i think problem in dynamicTyping: true today i try to find it

shrue348 commented 3 years ago

i resolve this problem i turn off dynamicTyping and add simple typing in transform function

parseConfig: { dynamicTyping: false, transform: (val: any) => { if (val.match(regExp)) { return (val.match(regExp)[1] || '') .split(',') .map((el: any) => ( Number(el) ? Number(el) : el )); } if (val === 'false') return false; if (val === 'true') return true; if (val === '[]') return []; if (val === '0') return 0; if (Number(val)) return Number(val); return val; }, },

benwinding commented 3 years ago

Great work @shrue348, glad to hear you got it sorted out!