js-IPFS / vue.js upload error - Object is not async iterable - vue.js

I have been working on js-ipfs (0.49.0) and this was working fine but I started getting some issues, anyway I have finally come back to look at the code again and the connection works fine but when I attempt to upload I get a new error
Object is not async iterable
I am not sure what that means or how to address in my code a lot of the examples are for react and not vue
Any pointers much appiciated.
methods: {
async getIpfsNodeInfo() {
try {
// Await for ipfs node instance.
node = await ipfs
// console.log(node)
// Call ipfs `id` method.
// Returns the identity of the Peer.
const { agentVersion, id } = await node.id()
this.agentVersion = agentVersion
this.id = id
// Set successful status text.
this.status = 'Connected to IPFS 😊'
} catch (err) {
// Set error status text.
this.status = `Error: ${err}`
}
},
onFileSelected(event) {
this.selectedFile = event.target.files[0]
this.saveIPFS()
},
async saveIPFS() {
try {
for await (const result of node.add(this.selectedFile)) {
this.fileContents = result
this.getIPFS()
}
} catch (err) {
// Set error status text.
this.status = `Error: ${err}`
}
},

ipfs.add returns a single object since ipfs#0.48.0 - you need to change:
async saveIPFS() {
try {
for await (const result of node.add(this.selectedFile)) {
this.fileContents = result
this.getIPFS()
}
} catch (err) {
// Set error status text.
this.status = `Error: ${err}`
}
},
to:
async saveIPFS() {
try {
this.fileContents = await node.add(this.selectedFile)
this.getIPFS()
} catch (err) {
// Set error status text.
this.status = `Error: ${err}`
}
},
See the blog post for more: https://blog.ipfs.io/2020-07-20-js-ipfs-0-48/#ipfs-add

Related

React Native getItemAsync Returns Promise

I am writing a storage class as such:
//Fallback if SecureStore fails
let data = {};
import * as SecureStore from 'expo-secure-store';
const Storage = {
set: async function (key, value) {
try {
console.log("Setting Item");
console.log(key);
console.log(value);
return await SecureStore.setItemAsync(key, value);
} catch (e) {
//fallback if set cookie fails
data[key] = value;
}
},
get: async function (key) {
try {
console.log("Gettimg Item");
console.log(key);
let result = await SecureStore.getItemAsync(key);
if (result) {
return await result;
}
return null;
} catch (e) {
console.error(e);
value = data[key];
return value;
}
}
export default Storage;
And Storage.set is called as such:
function() {
Storage.set("some_key", "some_value");
}
And here is an output of the console.log
Setting Item
user_id
4ce9dse7-650a-4ff5-955d-466a640de2c4
Setting Item
user_first_name
John
Setting Item
user_last_name
Doe
So apparently the items are being set. But each time I use the get function Storage.get(x), I get a promise back:
Promise {
"_A": null,
"_x": 0,
"_y": 0,
"_z": null,
}
What am I doing wrong here? I am using await twice but still returns a promise.

How to throw an error in nextjs (server) if the method is GET and supported but no parameter is passed?

export default function handler(req, res {
const {
method,
query: { pid },
} = req;
if (method === 'GET') {
if (pid) {
res.statusCode = 200;
res.end(`Post: ${pid}`);
} else {
try {
const error = 'No post id specified';
throw new Error(error);
} catch (err) {
res.statusCode = 400;
res.end(`error: ${err}`);
}
}
} else {
const error = `unsupported method ${method}`;
try {
throw new Error(error);
} catch (err) {
res.statusCode = 400;
res.end(`error: ${err}`);
}
}
}
If the route /posts/ is called (without specifying pid), the above will return the 404 page's HTML but not the intended error "No post id specified"
The unsupported route if-branch works correctly instead.
How to obtain the above-explained behavior?
Like this:
const Page = ({ error, pid }) => {
if(error) return <p>{error}</p>
return <p>The following Page ID was passed {pid}</p>
}
export async function getServerSideProps(context) {
const { pid } = context.query;
if(!pid || typeof pid === 'undefined'){
return {
props { error: 'No pid passed' }
}
}
return {
props: { pid }
}
}
export default Page;
On the server side you can get the passed param from context.query the param needs to have the same name as the file in this case [pid].js
Then you simply check if the param is null or undefined. If so you return an error to message in the props to the component. Otherwise you return the PID or do a server side fetch and return the data to the component.

How to prevent multi beginTransactions in Realmjs?

I create a function to handle transaction, then I call it to multi places. I got crash when another transaction not yet complete when I open new transaction.
Here my code:
const RealmMakeTransaction = async (action) => {
try {
realm.GetInstance().beginTransaction();
let response = await action();
realm.GetInstance().commitTransaction();
return response;
} catch (e) {
realm.GetInstance().cancelTransaction();
}
};
You can easily check if realm is already in transaction or not before calling beginTransaction() by calling realm.GetInstance().isInTransaction
Your code will look like :
const RealmMakeTransaction = async (action) => {
//use single instance
let realm = realm.GetInstance();
try {
if( realm.isInTransaction)
realm.cancelTransaction();
realm.beginTransaction();
let response = await action();
realm.commitTransaction();
return response;
} catch (e) {
realm.cancelTransaction();
realm.close();
}
};

React Native, fetch after async function

I have a problem that I do not know how to solve...
I have an api token saved in AsyncStorage, and when I want do fetch to rest I need this api token, but I do not know how to do it.
I have file Functions.js with AsyncStorage functions.
async retrieveItem(key) {
try {
const retrievedItem = await AsyncStorage.getItem(key);
const item = JSON.parse(retrievedItem);
return item;
} catch (error) {
console.warn(error.message);
}
},
getApiToken: function(){
try {
return Functions.retrieveItem('api_token');
} catch (error) {
console.warn(error.message);
}
},
File with fetch functions. (Api.js)
I tested with an asynchronous function, but not found...
async get(url) {
try {
var api = await Functions.getApiToken();
if (!api)
api = "";
let opt = {
method: 'get',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
}),
};
return fetch(baseUrl + url + api, opt);
} catch (error){
console.warn(error);
}
},
When I did the fetch function, it worked for me without problems
And the screen file Home.js
componentDidMount() {
Api.get('home').then( response => {
this.setState({
profiles: response.profiles,
});
});
}
Please modify your Functions.js code a bit -
async retrieveItem(key) {
try {
const retrievedItem = await AsyncStorage.getItem(key);
const item = JSON.parse(retrievedItem);
return item;
} catch (error) {
console.warn(error.message);
}
},
async getApiToken{
try {
let token = await retrieveItem('api_token');
return token;
} catch (error) {
console.warn(error.message);
}
}
Hope this helps you!

Possible Unhandled Promise Rejection(id:0)

I meet something strange and found no answer.
I met the warning as below:
Possible Unhandled Promise Rejection(id:0)
TypeError: undefined is not a function (evaluating '_api2.default.getResp(URL, "GET")'....
Below is shortened code like what my source code is.
The "Pass Code" works fine and "Warning Code" shows warning as above.
Why Api.getResp goes wrong but Api.loggedin.getResp works OK? They are so similar!!
Warning Code
const GetData = {
async fetchFeed() {
console.log(`Api = ${Api}`); // Api = [Object Object]
console.log(`Api.getResp = ${Api.getResp}`); // Api.getRest = undefined
const { success, content } = await Api.getResp(`${URL}`, 'GET');
if (success) {
.....
}
},
};
module.exports = FetchApi;
Pass Code
const GetData2 = {
async syncData(): void {
const { success, content } = await Api.loggedin.getResp(`${URL}`, 'GET');
.....
}
}
API
const Api = {
async getResp(url: string, method: string): Object {
try {
const response = await fetch(url,
{ method,
null,
{ 'content-type' : 'application/json' },
});
......
} catch (error) {
console.log(`fetch url: ${url}, error: ${error}`);
}
return result;
},
loggedin: {
async getResp(url: string, method: string): Object {
const accessToken = await this._getAccessToken();
....
return result;
},
},