export indexDB throws error "storeNames parameter was empty" - javascript

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;
}

Related

TypeError: Cannot read properties of undefined (reading 'push') when trying to push to a mongoDB

This is what the code looks like:
import { MongoClient } from 'mongodb';
import { config } from 'dotenv';
config();
export async function connectToCluster() {
let mongoClient;
const dbOptions; //Assume that this exists.
mongoClient = new MongoClient(process.env.MONGO_URI, dbOptions);
await mongoClient.connect();
return mongoClient;
}
db = await connectToCluster();
temp = db.db('Database').collection('data').find({}).limit(1).database.push(JSON.parse(data));
This gives the aforementioned error even though "database" is a field in the collection "data" in the db "Database".
Console-logging the entire thing up to .database gives undefined.

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(",");
});

Trouble with node-fetch Javascript

So I'm trying to build a weather app by using data from a weather API.
import fetch from 'node-fetch'
//fetch weather API
let weather
let getWeather = async() => {
let url = \https://api.openweathermap.org/data/2.5/weather?q=auckland&appid=c156947e2c7f0ccb0e2a20fde1d2c577`try {let res = await fetch(url)weather = await res.json() } catch (error) {console.log("error") } let weatherMain = weather.weather.map( el => el.description)if(weatherMain ="Rain"){console.log(weatherMain)// weatherImg = "[https://icon-library.com/images/raining-icon/raining-icon-1.jpg](https://icon-library.com/images/raining-icon/raining-icon-1.jpg)" } }console.log(getWeather())`
My problem is that I'm getting this error when running in vscode:
SyntaxError: Cannot use import statement outside a module
and this error when running in browser:
Uncaught TypeError: Failed to resolve module specifier "node-fetch". Relative references must start with either "/", "./", or "../".`
Not sure what exactly is going on, Can someone please explain what's happening?
I've tried fetch API once before and that time I didn't need to import fetch, so I'm pretty confused.
SS
Edit - Understood now, running in browser and in vscode is 2 different things. What works in the browser won't necessarily work in Node.js
When running in browser, there's no need to import fetch.
Thanks everyone.
let weather;
let getWeather = async () => {
let url = `https://api.openweathermap.org/data/2.5/weather?q=auckland&appid=c156947e2c7f0ccb0e2a20fde1d2c577`;
try {
let res = await fetch(url);
weather = await res.json();
console.log('weather', weather);
} catch (error) {
console.log(error);
}
let weatherMain = weather.weather.map((el) => el.description);
if ((weatherMain = 'Rain')) {
console.log('weatherMain', weatherMain);
let weatherImg =
'[https://icon-library.com/images/raining-icon/raining-icon-1.jpg](https://icon-library.com/images/raining-icon/raining-icon-1.jpg)';
return weatherImg;
}
};
const main = async () => {
const data = await getWeather();
console.log('data', data);
};
main();
Yes, you are right about no need to import fetch if you are running the js in the browser. But I see that you are importing node-fetch, this package is used to bring the fetch (window.fetch) for the node system.
But If you want to run it in the node, then you should know that the node doesn't support ES6 module. But you can user the experimental flag to run the code. e.g.
node --experimental-modules app.mjs

How to import a CSV file in ReactJs?

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.

Categories