I am unable to figure out what mistake i have done in the code
Whenever i am calling api, ipfs.add('hello') returns [object AsyncGenerator]
https://gateway.ipfs.io/ipfs/[object AsyncGenerator]
const addFile = async () => {
const Added = await ipfs.add('hello');
return Added;
}
const fileHash = await addFile();
return fileHash;
You can iterate over the result of .add() like so:
for await (const item of Added) {
console.log('item', item)
}
item { path: 'QmWfVY9y3xjsixTgbd9AorQxH7VtMpzfx2HaWtsoUYecaX',
cid: CID(QmWfVY9y3xjsixTgbd9AorQxH7VtMpzfx2HaWtsoUYecaX), size: 13 }
Related
const sources = files.map((file) => ({ path: `${file.index}${extension}`, content: file.buffer }));
for await (const result of ipfs.addAll(sources, { wrapWithDirectory: true })) {
Logger.log(`Uploaded: ${result.path}`);
if (result.path === "") {
rootCid = result.cid.toString();
}
}
const sources = files.map((file) => ({ path: `root/${file.index}${extension}`, content: file.buffer }));
for await (const result of ipfs.addAll(sources)) {
Logger.log(`Uploaded: ${result.path}`);
if (result.path === "root") {
rootCid = result.cid.toString();
}
}
The rootCid will be the same for both of the above codes, but { wrapWithDirectory: true } is very slower. Why is this?
This is because the execution time of ipfs' api method addAll is O(n) where n is the number of items in your input array
In other words, the more items you wish to add at once the longer it takes because each one creates an API call to add the item and each call must be awaited
//I tried to render data from the nested object, but retrieve the error message
useEffect(() => {
axios
.get('https://bodyshop.r2.software/wp-json/wp/v2/pages/2')
.then(response => {
const posts = response.data;
const tempObj = {};
for(let key in posts["post-meta-fields"]) {
const modifiedKey = key.replace('_','');
tempObj[modifiedKey] = posts["post-meta-fields"][key]
}
posts["post-meta-fields"] = tempObj;
setList(posts)
console.log(posts);
})
}, [])
// nested object
// posts = {
// ...
// 'post-meta-fields': {
// _bg_advantages_home: [''],
// _bg_banner_home: ['35'],
// _bg_info_1_home: ['41'],
// _bg_info_2_home: [''],
// _bg_offers_home: ['38'],
// _bg_sales_home: ['36'],
// _bg_video_home: ['']
// }
// ...
// };
//Example below
<div class="banner_title DrukFont">{posts["post-meta-fields"]["_bg_sales_home"][0]}</div>
//meyby problem with parse incorrect parse json method
When you transforming the data you do the following:
const modifiedKey = key.replace('_','');
which makes the underscore _ dissapear from the front of your keys so _bg_sales_home will be undefined in your transformed object and accessing [0] on undefined will throw an error.
You have to use bg_sales_home:
<div class="banner_title DrukFont">{posts["post-meta-fields"]["bg_sales_home"][0]}</div>
I'm curious if it's possible to return a destructured object on the same line it was destructured.
Current (working) examples:
using 2 lines
const itemList = json.map((item) => {
const { id, title } = item;
return { id, title };
});
1 line but not destructured
const itemList = json.map((item) => {
return { id: item.id, title: item.title }; // This also requires repeating the field name twice per instance which feels hacky
});
Is it possible to condense the body down to one line ?
example (doesn't work)
const itemList = json.map((item) => {
return { id, title } = item;
}
Destructure the callback parameters, and return an object:
const itemList = json.map(({ id, title }) => ({ id, title }))
In my states I have categories. In the categories array every each category have a settings column where I have saved json array string.
My question it is,how can I turn my string to object by filtering the response ?
My response:
[{"id":4,"name":"Vehicles","slug":"vehicles","settings":"[{"edit":true,"searchable":true}]","created_at":"2019-01-26 16:37:36","updated_at":"2019-01-26 16:37:36"},
This is my loading action for the categories:
const loadCategories = async ({ commit }, payload) => {
commit('SET_LOADING', true);
try {
const response = await axios.get(`admin/store/categories?page=${payload.page}`);
const checkErrors = checkResponse(response);
if (checkErrors) {
commit('SET_DIALOG_MESSAGE', checkErrors.message, { root: true });
} else {
commit('SET_STORE_CATEGORIES', response.data);
}
} catch (e) {
commit('SET_DIALOG_MESSAGE', 'errors.generic_error', { root: true });
} finally {
commit('SET_LOADING', false);
}
};
This is my SET_STORE_CATEGORIES:
const SET_STORE_CATEGORIES = (state, payload) => {
state.categories=payload.data;
state.pagination = {
currentPage: payload.current_page,
perPage: payload.per_page,
totalCategories: payload.total,
totalPages: payload.last_page,
};
};
Here I would like to add to modify the value ,to turn the string to object.
Had to add:
let parsed=[];
parsed=response.data.data.map((item)=>{
console.log(item);
let tmp=item;
tmp.settings=JSON.parse(item.settings);
return tmp;
});
response.data.data=parsed;
commit('SET_STORE_CATEGORIES', response.data);
You could map your response data as follows by parsing that string to an object :
let parsed=[];
parsed=response.data.map((item)=>{
let tmp=item;
tmp.settings=JSON.parse(item.settings);
return tmp;
});
commit('SET_STORE_CATEGORIES', parsed);
I'm running services to retrieve data from an API. Here is one of the services:
robotSummary(core_id, channel_name){
const params = new HttpParams()
var new_headers = {
'access-token': ' '
};
this.access_token = sessionStorage.getItem('access-token');
new_headers['access-token'] = this.access_token;
const myObject: any = {core_id : core_id, channel_name: channel_name};
const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;
const options = { params: new HttpParams(httpParams), headers: new_headers };
return this.http.get(this.baseURL + 'web_app/robot_summary/',options)
.subscribe(
res => console.log(res),
)
}
}
The data shows up properly on the console, but I still can't access the individual keys:
Here is how I call it:
ngOnInit(): void{
this.login.getData(this.username, this.password).subscribe((data) => {
this.robotSummaryData = this.getRobotSummary.robotSummary(this.core_id, this.channel_name);
console.log("robosummary"+ this.robotSummaryData)
});
}
When I call this function and assign it to a variable, it shows up on console as [object Object]. When I tried to use JSON.parse, it throws the error: type subscription is not assignable to parameter string. How can I access the data? I want to take the JSON object and save it as an Object with appropriate attributes. Thanks!
Do not subscribe inside your service, do subscribe in your component, change your service as follows,
robotSummary(core_id, channel_name){
const params = new HttpParams()
var new_headers = {
'access-token': ' '
};
this.access_token = sessionStorage.getItem('access-token');
new_headers['access-token'] = this.access_token; const myObject: any = { core_id: core_id, channel_name: channel_name };
const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;
const options = { params: new HttpParams(httpParams), headers: new_headers };
return this.http.get(this.baseURL + 'web_app/robot_summary/', options)
.map((response: Response) => response);
}
and then in your component,
ngOnInit(){
this.api..getRobotSummary.robotSummary(this.core_id, this.channel_name).subscribe((data) => {
this.data = data;
console.log(this.data);
});
}