How to import a CSV file in ReactJs? - javascript

I am trying to import a csv file that is in a folder called data on the same level as this function. I've tried to incorporate the solution I found on here, but no luck and I don't know what I need to modify.
getData.jsx
import React, { useState, useEffect } from 'react';
import Papa from 'papaparse';
export default function GetData(artist) {
const data = Papa.parse(fetchCsv);
console.log(data);
return data;
}
async function fetchCsv() {
const response = await fetch('data/artist_data.csv');
const reader = response.body.getReader();
const result = await reader.read();
const decoder = new TextDecoder('utf-8');
const csv = decoder.decode(result.value);
return csv;
}

Few problems I see here.
When you do fetch('data/mycsv.csv') you are essentially making a request to http://localhost:3000/data/mycsv.csv. Check the n/w tab and you will see the response returned is your html. React first loads your root page and then checks further for routes.
Some coding errors like - you haven't called the fetchCsv fun inside GetData function. Also you need to await for fetchCsv.
Solution:
Move your data folder which has your csv file to the public folder and make corrections to your code.
import React from 'react';
import Papa from 'papaparse';
async function GetData(artist) {
const data = Papa.parse(await fetchCsv());
console.log(data);
return data;
}
async function fetchCsv() {
const response = await fetch('data/mycsv.csv');
const reader = response.body.getReader();
const result = await reader.read();
const decoder = new TextDecoder('utf-8');
const csv = await decoder.decode(result.value);
console.log('csv', csv);
return csv;
}
I have tested the above code in my local and it works fine.

Related

export indexDB throws error "storeNames parameter was empty"

can anyone please help me out, I'm new to Dexie (Angular)
import Dexie from 'dexie';
import {ExportOptions, exportDB} from 'dexie-export-import';
const db = await new Dexie('myDB');
const blob = await exportDB(db);
I'm using exportDB method to export the indexDB with angular,
but it gives me error like
InvalidAccessError: Failed to execute 'transaction' on 'IDBDatabase': The storeNames parameter was empty.
Instead of exportDB function I have also tried like
const blob = await db.export(options);
But it throws error like TypeError: db.export is not a function
Try to call open on the database constructor:
import Dexie from 'dexie';
import { ExportOptions, exportDB } from 'dexie-export-import';
const exportDatabase = async (dbName) => {
const db = await new Dexie(dbName).open();
const blob = await exportDB(db);
return blob;
}

Sveltekit & Fleek (IPFS) import syntax problem?

I have managed to use fleek to update IPFS via straight javascript. I am now trying to add this functionality to a clean install of a svelteKit app. I think I am having trouble with the syntax around imports, but am not sure what I am doing wrong. When I click the button on the index.svelte I get the following error
Uncaught ReferenceError: require is not defined
uploadIPFS upload.js:3
listen index.mjs:412..........(I truncated the error here)
A few thoughts
I am wondering if it could be working in javascript because it is being called in node (running on the server) but running on the client in svelte?
More Details
The index.svelte file looks like this
<script>
import {uploadIPFS} from '../IPFS/upload'
</script>
<button on:click={uploadIPFS}>
upload to ipfs
</button>
the upload.js file looks like this
export const uploadIPFS = () => {
const fleek = require('#fleekhq/fleek-storage-js');
const apiKey = 'cZsQh9XV5+6Nd1+Bou4OuA==';
const apiSecret = '';
const data = 'pauls test load';
const testFunctionUpload = async (data) => {
const date = new Date();
const timestamp = date.getTime();
const input = {
apiKey,
apiSecret,
key: `file-${timestamp}`,
data
};
try {
const result = await fleek.upload(input);
console.log(result);
} catch (e) {
console.log('error', e);
}
};
testFunctionUpload(data);
};
I have also tried using the other import syntax and when I do I get the following error
500
global is not defined....
import with the other syntax is
import fleekStorage from '#fleekhq/fleek-storage-js';
function uploadIPFS() {
console.log('fleekStorage',fleekStorage)
};
export default uploadIPFS;
*I erased the api secret in the code above. In future I will store these in a .env file.
Even more details (if you need them)
The file below will update IPFS and runs via the command
npm run upload
That file is below. For my version that I used in svelte I simplified the file by removing all the file management and just loading a variable instead of a file (as in the example below)
const fs = require('fs');
const path = require('path');
const fleek = require('#fleekhq/fleek-storage-js');
require('dotenv').config()
const apiKey = process.env.FLEEK_API_KEY;
const apiSecret = process.env.FLEEK_API_SECRET;
const testFunctionUpload = async (data) => {
const date = new Date();
const timestamp = date.getTime();
const input = {
apiKey,
apiSecret,
key: `file-${timestamp}`,
data,
};
try {
const result = await fleek.upload(input);
console.log(result);
} catch(e) {
console.log('error', e);
}
}
// File management not used a my svelte version to keep it simple
const filePath = path.join(__dirname, 'README.md');
fs.readFile(filePath, (err, data) => {
if(!err) {
testFunctionUpload(data);
}
})

Make an http request and parse the data in React

I am trying to make an http request to my backend server (run on java springboot) with my React-based frontnend, which returns a string that I want to parse and assign to values. From what I have seen on the syntax pages, I want to believe that I am calling the request correctly. My error message mentions "Cannot read properties of undefined (reading 'split')", which I think means that split() is not a valid operation for js or React? Does anyone know what is the correct way to this?
import React from 'react';
import './App.css';
import Exchange from './Exchange'
import Recommendations from './Recommendations';
import axios from "axios";
function Middle(){
const response = axios.get("http://localhost:8080/run");
const data = response.data;
const dataArr = data.split(",");
return (
<div className = 'Middle'>
<h1>{data}</h1>
<Exchange name = "Coinbase" btcBuy = {dataArr[1]} btcSell = "" ethBuy = "" ethSell = ""/>
<Exchange name = "Binance" btcBuy = "" btcSell = "" ethBuy = "" ethSell = ""/>
<Recommendations/>
</div>
);
};
export default Middle;
It means that the data variable is not a string. Also you need to use useEffect if you want to fetch data.
import React, { useState, useEffect } from "react";
function Middle(){
const [data, setData] = useState([]);
useEffect(() => {
(async () => {
try {
const response = await axios.get("http://localhost:8080/run");
const data = response.data;
setData(data); // use split if you have to, I dont think you need that.
} catch(err) {
console.error(err);
}
})()
}, [])
Actually you do not read the response properly, as it is an asynchronous operation and your response is undefined at the time you make operations on it sequentially.
You have to place your code in the body of .then, like this:
let dataArr = [];
axios.get("http://localhost:8080/run")
.then(response => {
const data = response.data;
dataArr = data.split(",");
});

multiple url variable async/await axios

Probably this is a very stupid question, i'm new in Node.js and javascript, so please forgive me if the question is not properly explained or the answer is simple...
I'm trying to send 2 variables thru a url... When i send only 1 variable (artist=${term}) work all good, but I'm really stuck with about how to send 2 variables thru the url (&artist=${term1}&album=${term2})
I've work on this code so far which for 1 variable is working well... but i have no idea how to add a second or a third variable to the request:
File 1: "./services/albumInfo.js"
import { BRV_API } from '../../config';
import axios from 'axios';
import dotenv from 'dotenv';
const ALBUM_INFO = 'method=album.getinfo';
dotenv.config();
const doRequest = async (url) => {
return await axios.get(`${BRV_API}/${url}&api_key=${process.env.API_KEY}&format=json`);
};
export const infoAlbum = async (term) => {
return await doRequest(`?${ALBUM_INFO}&artist=${term}`);
};
File 2: "./repositories/albumInfo.js"
import { infoAlbum } from '../repositories/albumInfo';
import status from 'http-status';
export const albumInfo = async (req, res, next) => {
try {
const { query } = req;
const { data } = await infoAlbum(query.name);
const response = data;
res.status(status.OK).send(response);
} catch (error) {
next(error);
}
};
I know that my problem is in this part of the code (I guess)
export const infoAlbum = async (term) => {
return await doRequest(`?${ALBUM_INFO}&artist=${term1}&album=${term2}`);
};
I've been searching, and i've seen some solution, like this one, but i just don't understand those solutions or how to apply on my code (sorry for that, im a very new on this)
Any good soul who can help this newbie? (if can explain the why of the solution as well, for understand, will be amazing!!)
Thanks in advance!!
Axios provides parameters that can be added custom as the following
const your_url = process.env.URL
const infoAlbum = await axios.get(your_url,{
params: {
artist: term,
album: term2,
api_key: process.env.API_KEY,
format:'json'
}
})
console.log(infoAlbum.data.args)
note: your_url without any more parameters.
So,
I've found a solution, which is pretty ugly, but so far is working, if someone have a better option, will be amazing to know:
File 1: repositories/albumInfo.js, I've just add the console (as per #Alex028502 suggestion), to know what the code was returning:
import { BRV_API } from '../../config';
import axios from 'axios';
import dotenv from 'dotenv';
const ALBUM_INFO = 'method=album.getinfo';
dotenv.config();
const doRequest = async (url) => {
const fullurl = `${BRV_API}/?${ALBUM_INFO}${url}&api_key=${process.env.API_KEY}&format=json`;
console.log('full url is', fullurl);
return await axios.get(fullurl);
};
export const infoAlbum = async (term) => {
return await doRequest(`&${term}`);
};
File 1: services/albumInfo.js: I change the behaviour of 'infoAlbum' to make the request from his side:
import { infoAlbum } from '../repositories/albumInfo';
import status from 'http-status';
export const albumInfo = async (req, res, next) => {
try {
const { query } = req;
console.log(query);
const { data } = await infoAlbum('artist=' + query.artist + '&album=' + query.album);
const response = data;
res.status(status.OK).send(response);
} catch (error) {
next(error);
}
};
I know that probably this is not the very best way to walk away from the problem, but so far is what i have.... any other better option about how to capture the second or third parameter of the url request and then add them to the final url?
Best!

how to fetch a csv file simply using fetch method in javascript in a react application?

this is my first question on stackoverflow, i search and tried lot of solutions but i finally decided to ask for help here.
I have seen a similar question without answer here:
Cannot fetch .csv data in React
I use reactJs to create a little application and as a database, i want to use a csv file.
i would like to use the fetch method to parse my data (my csv file),
whatever i do, the console.log(data) who should return me the contents of my csv, rather return anything to me instead....
my code :
async function getData() {
const response = await fetch('./private/BookList.csv', {
headers : {
'content-type': 'text/csv;charset=UTF-8'
}
})
.catch(function() {
console.log("error");
});
const data = await response.text();
console.log(data);
}
in my développer tools , the console.log display this:
console.log
which returns me absolutely anything!
my CSV file contain the following lines :
TITRE,EDITEUR,DIMENSIONS ~ (cm),TYPE,COLLECTION,ETAT,PRIX (€),stock
HOUSE OF M,PANNINI COMICS,17*26,RELIÉ,MARVEL,COMME NEUF,20,true
i found the issue : it was because in react the CSV file must be imported
(the weird thing was i do that at the begining but i changed it maybe because my code would'nt work for another reason at this time.
the following code return me an array of titles from my CSV file!
import React, { Component } from 'react';
import { render } from '#testing-library/react';
import './App.css';
import FilterableBooksTable from './Components/FilterableBooksTable';
import DATA from './private/BookList.csv';
const DATA_ARRAY = [];
async function getData() {
const response = await fetch(DATA, {
headers : {
'content-type': 'text/csv;charset=UTF-8'
}
})
.catch(function() {
console.log("error");
});
const data = await response.text();
// console.log(data);
const rows = data.split((/\r?\n|\r/)).slice(1);
// console.log(rows[1]);
rows.forEach(elt => {
const colums = elt.split(';');
const titre = colums[0];
// console.log(titre);
DATA_ARRAY.push(titre);
})
console.log(DATA_ARRAY);
}
getData();
function App() {
return (
<div className="App">
<header className="App-header">
<div>
{/* <FilterableBooksTable books={DATATOPARSE}/> */}
</div>
</header>
</div>
);
}
export default App;
result

Categories