Unable to access element from array of JSON objects - javascript

I am trying to access the specific elements of an array of JSON objects. To test I simply have:
{console.log(this.state.stockCharts)}
This returns (in browser):
This is great, but now I want to access a specific element. Say the first element. I type:
{console.log(this.state.stockCharts[0])}
And the browser is like: nah mate
undefined
It's probably something really simple, but I have been banging my head against my keyboard for the past 45 minutes and nothing has worked. Thanks guys!
Edit 1 (For Akrion)
The query that I am using to access the API is:
https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY&symbol=MSFT&apikey=demo
This is what I get back from the call:
I call this API twice, and after I get a response back I push it to my stockCharts array:
this.state.stockCharts.push(result)
Edit 2 (For Beginner)
I initialize the state how you would normally do it:
this.state = {
stockCharts: []
}

I verified with the api given in my local and I am able to get the data.
First thing the way you push api response to stockCharts is not recommended. Which means direct mutation of the state is not recommended.
You can push api response in the following way
this.setState(prevState => ({
stockCharts: [...prevState.stockCharts, result]
}));
Now in render
render(){
this.state.stockCharts.map((data, i) => {
console.log("data", data); // this will give each object
console.log("Meta Data", data["Meta Data"]); //This will give meta data information
console.log("Weekly Time Series", data["Weekly Time Series"]);// this will print weekly time information
});
return(
)
}
Is this what your expectation?

It might be because you mutate the state which is not recommended.
try instead of calling this.state.stockCharts.push(result) do this.setState({stockCharts: [...this.state.stockCharts, result]})
https://reactjs.org/docs/state-and-lifecycle.html

Related

Created a new object, then put an array after it in a loop to patch a property, it works but I dont know why?

I'm working with JavaScript in Node.js and using Express with some mongoose and following a well known RESTful API tutorial on youtube, I've come to patching the API and have been trying to understand why the following code works for sometime now;
updateItem = {};
for (const changes of req.body) {
updateItem[changes.propName] = changes.value;
}
Product.updateOne({ _id: id }, { $set: updateItem })
The rest is just your standard .then().catch() to send the response status, but I'm lost on how creating the object then placing it before an array works to update a value.
It's my current understanding that the object must be instantiated before use, I couldn't just put brackets there and have it work, even if I wasn't using it to set something later. Then I loop through the changes from the request body which must be an array to allow looping, but here's where I get lost.
Does the array of iterated prop names changes.propName get placed inside the updateItem object which is then set to the changed values from the array of properties that are being changed? Do I need to understand $set syntax more? I'm struggling to pick it apart to make it longer or simpler but better to understand.
This is the json array setup I'm passing for testing through postman if it helps;
[
{
"propName": "name", "value": "placeholder user"
}
]
I was unable to find anything to help me understand the interactions going on here, I haven't seen something like this before either but please redirect me if this has already been asked.

Access nested JSON data in ReactJS when clicking Search?

I have tried several other options on how to do this, such as
How to read a nested JSON in React?
Can't access nested JSON Objects in React
I am trying to query the API when I click "Search". Currently, when I click "Search", the API queries the correct URL, but I am having trouble accessing the returned data. The data that is sent back looks like this:
{
"option_activity": [
{
"id": "5f033b253c8cf100018a312f",
"bid": "0.6",
"ask": "1.0",
"midpoint": "0.8",
"updated": 1594047269
},
{
"id": "5f033b253c8cf100018a312f",
"bid": "0.6",
"ask": "1.0",
"midpoint": "0.8",
"updated": 1594047269
},
With hundreds of these items. What it looks like in the console:
What I am doing to query the api:
fetchData() {
var val = this.state.searchedValue;
var url = "URL/TO/API"
fetch(url)
.then(res => res.json())
.then((res) => {
const itemsList = res.option_activity;
this.setState({
items: itemsList
},
function () {
console.log(itemsList);
}
);
// console.log(this.state.items)
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
console.log(error);
},
// console.log(this.state.items)
)
}
While the network logs the response from the API, the console log just logs an empty array "[]" for this.state.items, which is initialized to an empty array. How can I save the contents of "option_activity" into an array "items", where I can access the id, bid, ask, midpoint etc through this array of items?
So, items[0] would have items[0].id, items[0].midpoint, etc accessible.
Thanks in advance
Solution is in the comments of the correctly marked answer
Are you hitting an API URL on a different domain? If so, you may well be actually getting a CORS error. If you try to programmatically hit an endpoint on another domain, the browser will check for specific headers to ensure the API allows you to do that. If it doesn't see those headers, it will throw an error (which you should see in your console). The network tab will still show the expected payload, but it won't be made accessible to you in Javascript.
Right now, you are only logging to the console on an error. So, if you are seeing the response in the network tab, but are always ending up in the error handler, that indicates something is wrong with the response (CORS, or somehow maybe you are returning malformed data that can't be parsed as JSON).
You should also note that your current log isn't particularly useful. You are only ever printing out the old value of items. Since you clearly never set it (note that you are in the error handler), you would expect this value to be whatever it was before trying to set the value of items (presumably the initial empty array).
First, you don't need to use map to convert the returned activity list if you want to access to id, bid, etc.
const itemsList = res.option_activity;
this.setState({
items: itemsList
});
Second, if you want to read state right after using setState, you need to use a callback, similar to the following code snippet.
this.setState({ boardAddModalShow: true }, function () {
console.log(this.state.boardAddModalShow);
});
This is because according to React docs
setState() does not immediately mutate this.state but creates a
pending state transition. Accessing this.state after calling this
method can potentially return the existing value. There is no
guarantee of synchronous operation of calls to setState and calls may
be batched for performance gains.

Angular Http subscribe - cannot assign to variable in component

I want to retrieve data from api and assign it to some value inside the angular component. In subscribe I'm trying to assign the data to loggedUser and then call function inside this subscribe to navigate to another component with this received object. Unfortunately I got the error : The requested path contains undefined segment at index 1. I want to have this object set outside the subscribe too. How can I achieve this?
logIn() {
this.portfolioAppService.logIn(this.loggingUser).subscribe((data) => {
this.loggedUser = data;
console.log(this.loggedUser);
console.log(data);
this.navigateToProfile(this.loggedUser.Id);
});
}
navigateToProfile(id: number) {
this.router.navigate(['/profile', id]);
}
console output
You are using an incorrectly named property when calling navigateToProfile.
From your console output, I can see that the data object in the subscribe looks like this:
{
id: 35,
// ..
}
But you are calling the function like this:
this.navigateToProfile(this.loggedUser.Id);
Instead, use the property id (lower case)
this.navigateToProfile(this.loggedUser.id);
To narrow this problem down in the future, try being more specific in your testing. Humans are good at seeing what they want to see and will assume the problem is more complicated than it is. If you had tried console.log(this.loggedUser.Id), you would have seen the result undefined, and worked out the problem yourself.

How to paginate getting bulk data from firebase with axios?

Assuming I have 1000+ blog posts. What will be the best practice to get data from firebase using axios to store in nuxtServerInit?
Can I somehow get the first 10 blog posts first during the first load and get even more data later on?
Right now I have vuex action as following:
nuxtServerInit(vuexContext, context) {
return axios
.get('https://my-blog.firebaseio.com/posts.json')
.then(res => {
const postsArray = []
for (const key in res.data) {
postsArray.push({ ...res.data[key], uid: key })
}
vuexContext.commit('setPosts', postsArray)
})
.catch(e => context.error(e))
},
You're using the REST API to access the Firebase Database. To retrieve a limited number of items, use a limit query.
https://my-blog.firebaseio.com/posts.json?limitToFirst=10
Since a limit only makes sense when you know how the items are order, you'll want to also order the items, i.e. on their key:
https://my-blog.firebaseio.com/posts.json?orderBy="$key"&limitToFirst=10
Note that the results may not be ordered, since the order of properties in a JSON object is undefined. So the result will contains the first 10 posts, but it may not show them in the right order.
Next step is to get the next 10 items. Unlike on most traditional databases, Firebase doesn't support an offset clause on its queries. So you can't tell it to skip the first 10 items to get to the next 10.
Instead Firebase queries use anchors/ranges: you must know the last item of the previous page to build the query for the next page. Say that the 10th post had a key of keyOfPost10, then you can get the next page with:
https://my-blog.firebaseio.com/posts.json?orderBy="$key"&startAt="keyOfPost10"&limitToFirst=11
We need to retrieve 11 posts here, since we're also getting the 10th post. That also means you'll need to filter the overlapping post in your client code.

unable to view new table data after concat - Ionic 3 Angular 4

I'm using ionic's events to pass data from page to page. In this instance I'm passing an array to another page, let's say with two objects. The data I'm wanting to add to is called dataOne and I'm using a life cycle function so that when the user enters the page they will be automatically tested from this function whether or not there is an event to be concatenated onto dataOne. The issue is, the data isn't being added. I'm able to retrieve the data but nothing happens to the table, as I'm still getting the same result.
ts
ionViewWillEnter(){
this.events.subscribe('market', (dataTwo) => {
return this.dataOne = this.dataOne.concat(dataTwo)
})
}
What is 'Market' ? dataOne is array? In my opinion,
dataOne: any[]=[];
...
this.events.subscribe((dataTwo) =>{
this.dataOne.push(dataTwo.market); // if market you want to catch data
}

Categories