I am uploading the data from excel file using react-excel-renderer, storing the excel render response containing column & rows response in state and passing to other component.
Expected Use-case result:- I am fetching the data from excel using render storing the values in states(rows). I am passing the state to other component where i need these values to pass in API .
The data stored is in nested form. Can you please let me know how to get data separately stored under array in props. Attached is the screenshot.
Excel Render code:-
changeHandler(event) {
let fileObj = event.target.files[0];
//just pass the fileObj as parameter
ExcelRenderer(fileObj, (err, resp) => {
if (err) {
console.log(err);
} else {
this.setState({
cols: resp.cols,
rows: resp.rows,
});
}
});
}
Code to fetch the prop data:-
for (let i = 0; i < this.props.data.length; i++) {
let stDate = this.props.data[i].startDate;let TripName = this.props.data[i].TripName;
let totalFare = this.props.data[i].totalFare;
let FirstName = this.props.data[i].FirstName;
let LastName = this.props.data[i].LastName;
let Currency = this.props.data[i].Currency;
}
You can use an Array method
Still not 100% sure what your final data should look like, but it feels like you're using 2 arrays. 1 as the key and 1 as the value.
So to combine these 2 we can use Reduce
const keys = data[0];
const values = data[1];
keys.reduce((acc, keys, index) => {
return {...acc, [key]: values[index]}
}, {})
That will return an object of key values.
Related
My goal is to get multiple data based on a list of data the customer requested so I put the codes inside useEffect. If the array contains the list of things the customer wants, then it grab those data from the server so the user can manipulate it. So far, it works fine but when the database updates, onValue is not triggered to grab the new data to update the render.
Here is my code. Thank you for helping me in advance.
// Getting data
useEffect(() => {
if (empDataArr.length > 1) {
let fromDay = parseInt(dateHandler(startDate).dateStamp);
let toDay = parseInt(dateHandler(endDate).dateStamp);
let tempLogArr = [];
empDataArr.forEach((emp) => {
let qLogEvent = query(child(shopRef(shopId), emp.id + "/log_events"), orderByChild("dateStamp"), startAt(fromDay), endAt(toDay));
// This is the part I need help
onValue(qLogEvent, (snap) => {
let logEventArr = [];
let val = snap.val();
if (val === null) {
} else {
Object.keys(val).forEach((key) => {
let id = key;
let dateStamp = val[key].dateStamp;
let direction = val[key].direction;
let time = val[key].timeStamp + "";
let timeStamp = time.substring(8, 10) + ":" + time.substring(10, 12);
logEventArr.push({ direction: direction, timeStamp: timeStamp, dateStamp: dateStamp, id: id });
});
tempLogArr.push({
id: emp.id,
logEvent: logEventArr,
});
}
});
});
setLogDataArr(tempLogArr.map((x) => x));
}
}, [empDataArr, shopId, startDate, endDate]);
useEffect(() => {
console.log(logDataArr);
}, [logDataArr]);
I have tried using return onValue() and const logData = onValue() but they do not work (and I do not expect the former one to work either).
I want to add some data on the bookChapters object, like a random id and inside of it the name of the chapters, I tried this but it doesn't work, after I add the previous data I also want to add a new object "takeAways", like the previous one, inside the random id object.
export const createNewChapter = (bookId, inputText) => {
return async dispatch => {
dispatch(createNewChapterStart());
try {
firebase
.firestore()
.doc(`Users/${bookId}/bookChapters/${inputText}`)
.onSnapshot(querySnapshot => {
//There I want to add the chapters to the firestore database
});
dispatch(createNewChapterSuccess(inputText));
} catch (error) {
dispatch(createNewChapterFail(error));
console.log(error);
}
};
};
I wanna know how to do add from scratch the bookChapters object
The database screenshot shows that the bookChapters object is a map. So to add (populate) this object you need to generate a simple JavaScript object with some properties as “key: value” pairs.
Something along these lines, making the assumption the chapter titles are in an Array:
function arrayToObject(arr) {
var obj = {};
for (var i = 0; i < arr.length; ++i) {
obj[i] = arr[i];
}
return obj;
}
const chapterList = ['Intro', 'Chapter 1', 'Chapter2', 'Conclusion'];
const bookChaptersObj = arrayToObject(chapterList);
firebase.firestore().doc(`Users/${bookId}`).update(bookChaptersObj);
Or, if the document does not already exist:
firebase.firestore().doc(`Users/${bookId}`).set(bookChaptersObj, {merge: true});
Is this the correct way to store multiple observable maps within a store.
I'm relatively new to working with observables and MobX. I have a store for any maintenance domain object. For example "Institution Types". Instead of using a map for each I initiate a new map based off of an enum created:
maintenanceRegistry = new Map<string, any>();
selectedMaintenanceList = new Map<string, any>();
constructor() {
makeAutoObservable(this);
Object.values(MaintenanceTypeEnum).forEach((value) => {
this.maintenanceRegistry.set(value, new Map<string, any>());
});
}
And then on my onClick I set the selectedMaintenance map using the enum as the key:
if (maintenanceRegistry.get(MaintenanceTypeEnum.InstitutionTypes).size <= 1) {
loadMaintenance<InstitutionType>({apiPath: '/institutionTypes'});
} else {
setSelectedMaintenanceList(MaintenanceTypeEnum.StructureCategories);
}
When I load the data it updates my table and values however when the data has already been fetched the table data is not being updated.
To fetch the data I am using a computed function:
get maintenanceValues() {
var mv: any[] = [];
[...this.selectedMaintenanceList.values()].map((value: {value: any}, i) => {
mv.push(value);
})
return mv;
}
and then I map the data without the id property as its a guid and unnecessary:
const data = (maintenanceValues).map(value => {
const { id, ...noId } = value;
return noId
})
I am scraping data from a URL containing a csv. The format of the data I'm scraping is like this:
I am doing this in Node.js and using the nodejs-requestify package: https://www.npmjs.com/package/requestify
When I console the response.getBody() it's in the exact same format as the screenshot provided.
I am trying to convert this to a JSON array that I can iterate over in a loop to insert the values into a database, however, am struggling to get the data into JSON format.
I've tried splitting the array in multiple ways (comma, single quote, double quote). I've tried JSON.parse() and JSON.stringify() (and both in combination).
Here is the code I'm using. Ultimately when I console.log rows in the loop, this is where it should be in JSON format, however, it's just coming in as comma separated values still.
requestify.get('URL').then(function(response) {
// Get the response body
var dataBody = response.getBody();
var lineArray = dataBody.split('\r\n');
var data = JSON.parse(JSON.stringify(lineArray));
for(var s = 0; s < data.length; s++) {
var rows = data[s];
console.log(rows)
}
});
There is a basic misundertanding I think
var lineArray = dataBody.split('\r\n');
lineArray now contains something like
"a", "b", "c"
but for doing something like
var data = JSON.parse(lineArray);
you need lineArray to be
{ "a":"1", "b":"2", "c":"3" }
I think you need something like
const lineData = lineArray.split(',');
const keys = ["name", "age", "gender"];
const jsonLineData = {};
keys.forEach((key, index) => {
jsonLineData[key] = lineData(index);
});
I solved this by using csvtojson and aws-dsk since my csv is hosted on S3.
async function startAWS(db){
//Retrieve AWS IAM credentials for the 'master' user
var awsCredentials;
try{
awsCredentials = await retrievePromise(config.get('aws'));
}
catch (e) {
console.log({error:e},'startAWS error');
}
//Setup the AWS config to access our S3 bucket
AWS.config = new AWS.Config({
accessKeyId : awsCredentials.principal,
secretAccessKey :awsCredentials.credential,
region:'us-east-1'
});
//Call S3 and specify bucket and file name
const S3 = new AWS.S3();
const params = {
Bucket: '***',
Key: '***' //filename
};
//Convert csv file to JSON
async function csvToJSON() {
// get csv file and create stream
const stream = S3.getObject(params).createReadStream();
// convert csv file (stream) to JSON format data
const json = await csv().fromStream(stream);
//connect to DB and continue script
db.getConnection()
.then(async (conn) => {
if(json.length) {
for(var s = 0; s < json.length; s++) {
var rows = json[s];
const insert = await conn.query(
'SQL HERE'
);
}
}
})
};
csvToJSON();
}
How can I access the value exist from an array? I think I didn't pass the array inside? Any help or advice
var isExist = this.props.isFavorite(this.props.code);
console.log(isExist)
I have this variable isExist containing the response from console below.
[]
client: [id: "LvR05w9v9xrC3r4V1W8g", exist: true]
length: 1
_proto_:Array(0)
How can I access the exist in my array? When I tried isExist[0].exist I'm getting an error. Any help?
isExist.exist = Undefined
isExist[0].exist = TypeError: Cannot read property 'exist' of undefined
favorite method where I am accessing and pushing data to the array
export const isFavorite = (data) => dispatch => {
let exist = [];
var clientQuery = firebase.firestore().collection(path).where('client_id', '==', data);
clientQuery.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
var data = [];
data.id = doc.id;
data.exist = doc.exists;
exist.push(data)
});
});
return exist;
}
isFavorite returns a function which takes one argument dispatch and returns exist array. You seem to use async code to populate exist array. So when that function returns exist is an empty array []. You either need to continue using promises or use await. And you need to call the function returned by isFavorite.
If this.props.isFavorite and const isFavorite are not the same then add the code for this.props.isFavorite please.
You're creating an array Object. Then the array object {data}[]. So the problem is, the data is actually not only an array but also an object.
Try doing this.
var data;
data.id = doc.id;
data.exist = doc.exist;
exist.push(data);
Now you will have exist data that would be an array of Object.
Then iterate from it.
exist[0].id;
//or try
exist[0].data.id;
//Depends on how you implement your data.
Since client array doesn’t contain object with keys and values I would recommend you to try with array of index with split() to get id value and exist value from array like
Like
var isExist = this.props.isFavorite(this.props.code);
var id = isExist.client[0];
var exist = isExist.client[1];
var idValue = id ? id.split(': '): '';
console.log(idValue);
const existValue = exist ? exist.split(': '): false;
console.log(existValue);
And here change data = []; array to data ={}; object
querySnapshot.forEach((doc) => {
var data = {};
data.id = doc.id;
data.exist = doc.exists;
exist.push(data)
});