Data binding not working on React with object properties - json

//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>

Related

Mapping from JSON Get Request. Undefined

I am trying to connect to the USDA Food Central database using an API.
let uri = encodeURI(`https://api.nal.usda.gov/fdc/v1/foods/search?api_key=${MY_API_KEY}&query=${search}`)
I want to use the API to map certain fields.
class AddFoodItemList extends Component {
static contextType = AddFoodContext;
render() {
const listItems = this.context.FoodSearch.map((foods) =>
<FoodItem
key={foods.brandOwner}
brandOwner={foods.brandOwner}
fdcId={foods.fdcId}
/>
);
return (
<div id="AddFoodItemList">
{listItems}
</div>
);
}
}
export default AddFoodItemList;
The returned JSON is this screenshot attached:
Returned JSON
I am getting an error, TypeError: Cannot read property 'map' of undefined.
Why do you think this is the case? Any sort of help or suggestions are appreciated!
You are attempting to access a property FoodSearch on the value of your AddFoodContext provider. The error tells you that this property is undefined. If the object in your screenshot is the value of your context then you want to access the property foods instead. This is an array whose elements are objects with properties brandOwner and fdcId.
On your first render this data might now be loaded yet, so you should default to an empty array if foods is undefined.
It's honestly been a long time since I've used contexts in class components the way that you are doing it. The style of code is very dated. How about using the useContext hook to access the value?
const AddFoodItemList = () => {
const contextValue = useContext(AddFoodContext);
console.log(contextValue);
const listItems = (contextValue.foods || []).map((foods) => (
<FoodItem
key={foods.fdcId} // brandOwner isn't unique
brandOwner={foods.brandOwner}
fdcId={foods.fdcId}
/>
));
return <div id="AddFoodItemList">{listItems}</div>;
};
Here's a complete code to play with - Code Sandbox Link
const MY_API_KEY = "DEMO_KEY"; // can replace with your actual key
const getUri = (search) => `https://api.nal.usda.gov/fdc/v1/foods/search?api_key=${MY_API_KEY}&query=${encodeURIComponent(search)}`;
const AddFoodContext = createContext({});
const FoodItem = ({ brandOwner, fdcId }) => {
return (
<div>
<span>{fdcId}</span> - <span>{brandOwner}</span>
</div>
);
};
const AddFoodItemList = () => {
const contextValue = useContext(AddFoodContext);
console.log(contextValue);
const listItems = (contextValue.foods || []).map((foods) => (
<FoodItem
key={foods.fdcId} // brandOwner isn't unique
brandOwner={foods.brandOwner}
fdcId={foods.fdcId}
/>
));
return <div id="AddFoodItemList">{listItems}</div>;
};
export default () => {
const [data, setData] = useState({});
useEffect(() => {
fetch(getUri("cheese"))
.then((res) => res.json())
.then(setData)
.catch(console.error);
}, []);
return (
<AddFoodContext.Provider value={data}>
<AddFoodItemList />
</AddFoodContext.Provider>
);
};

ipfs.add() returns Object [AsyncGenerator] {}

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 }

Json string array to object in Vuex

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

Why isn't my function returning the proper JSON data and how can I access it?

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

angular http post send complex objects

My Service
public submitBooking(createBooking: CreateBooking) {
const body = this.getSaveBookingRequestBody(createBooking);
//const json = JSON.Stringify(body) //It throws 415 error
return this.httpClient.post(this.baseUrl + 'Save', body )
.subscribe();
}
private getSaveBookingRequestBody(createBooking: CreateBooking): any {
const body = {
'Booking': {
'Header': this.getBookingHeader(createBooking), //It works fine.
'Items': [this.getBookingItems(createBooking)],
},
'TestOnly': !environment.production,
};
this.Logger.log(body);
return body;
}
private getBookingItems(createBooking: CreateBooking): any {
const bookingItem = {
'CountryOfOrigin': createBooking.booking.countryoforigin,
'VehicleValue': createBooking.booking.valueofvechicle,
'SerialNumber': createBooking.booking.bookingNumber,
'Description': createBooking.booking.description,
'Mobility': createBooking.booking.mobility,
'Currency': createBooking.booking.currency,
'Weight': createBooking.booking.weight,
'Year': createBooking.booking.year,
'Cbm': createBooking.booking.cbm,
//This is an array it doesn't work.
'SubUnits':[
createBooking.booking.relatedVehicles.forEach(element => {
const units = {
'RelationType': element.relation,
'Weight': element.weight,
'Year': element.year,
};
})],
};
return bookingItem;
When i create POST body the SubUnits always empty in WEB API.
How to loop through array and create an object for sending as body.
My angular model and WEB-API object are different
I have also tried the JSON.Stringify(unitsArray) and returning it to SubUnits
const unitsArray = [];
createBooking.booking.relatedVehicles.forEach(element => {
const units = {
'RelationType': element.relation,
'SerialNumber': element.chassisno,
'Weight': element.weight,
'Year': element.year,
};
unitsArray.push(units);
});
SubUnits : JSON.stringify(unitsArray); // It also doesn't work with API.
Version :
Angular 5
Typescript 2.4.2
const bookingItem = {
...
'SubUnits': [
createBooking.booking.relatedVehicles.forEach(element => {
const units = {
'RelationType': element.relation,
'Weight': element.weight,
'Year': element.year,
};
})
]
...
};
This loop doesnt fill the array in bookingItem.SubUnits. Array.forEach does not return a value. Besides that, the variable units is never used. What you can do instead is create a new array using Array.map.
'SubUnits': [
createBooking.booking.relatedVehicles.map(element => ({
'RelationType': element.relation,
'Weight': element.weight,
'Year': element.year
}))
]
This makes an array with 1 array element from createBooking.booking.relatedVechiles. I am not sure if that's what you are going for, but it is in your OP.
Have you tried to not use JSON.stringify? Just use:
SubUnits :unitsArray;