Can't access array after passing it to state, but can access it before - javascript

I have an pseudo-object is inside my state. I've been able to access through a couple layers, but when I reach the array inside the object Im getting undefined errors.
UPDATE: Its something wrong with how I pass lambdaReturnObject to the state which isn't letting me access the array, tested with lambdaReturnObject.campaigns[0].campaignName and it worked.
handleSearch() {
//data to use to query backend
let campaignId = this.refs.campaignInput.value
let marketplace = this.refs.marketplaceInput.value
//using local copy of backend data, production should call backend fo this instead
let lambdaReturn = "{\"advertiser\":{\"advertiserId\":\"1\",\"enforcedBudget\":0.1},\"campaigns\":[{\"campaignID\":\"1\",\"campaignName\":\"fake\",\"createDate\":11111,\"creationDate\":1111,\"startDate\":1111,\"endDate\":1111,\"dailyBudget\":0.1,\"internal\":{\"budgetCurrencyCode\":\"USD\",\"inBudget\":true},\"enforcedBudget\":0.1,\"budgetCurrencyCode\":\"USD\",\"budgetPacingStrategy\":\"asp\",\"budgetType\":\"averageDaily\",\"status\":\"enables\",\"internalStatus\":\"enabled\"}],\"campaignID\":\"1\"}"
let lambdaReturnObject = JSON.parse(lambdaReturn)
this.setState({
apiData: lambdaReturnObject
})
}
When I try and go to the array inside, I get the following error
<h3>Campaigns :{console.log(this.state.apiData.campaigns[0].campaignName)}</h3>
Cannot read property '0' of undefined
This means I am accessing it the wrong way, but I looked at other posts (Accessing Object inside Array) and I thought that this was right. Though I am definitely wrong or else I wouldn't be writing this.

JSON.parse() is synchronous function, so set state wont be called till, JSON.parse() executes completely and returns the object.
Still You can try following
Call JSON.parse() using a try-catch block like below and see if it works. Also it is error free way of parsing your stringified objects.
try {
let lambdaReturnObject = JSON.parse(lambdaReturn)
this.setState({
apiData: lambdaReturnObject
})object
}
catch (err) {
// Do error handling here.
}
Use optional chaining, and try to access your object like this.state.apiData.campaigns?.[0].campaignName; this won't give error even if compaigns is undefined.
Refer : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Depending on what is happening. The call to get campaigns[0] is getting resolved before the API call finishes. You can try a promise or async await to make sure the object is retrieved from the API call before you attempt to access it.
Do you happen to have a code snippet of is being used to get the data?

The error was that render() calls right as the page is booted up. At that time the object is not stored in my state so trying to call
this.state.objects.innerObject.property
would fail because I declared objects in my state, innerObject could be counted as null before the object is actually loaded in so it wouldn't throw an error. But property would throw an error because innerObject as we know, is null.
Fix by using an if statement before rendering the page to see if the object is actually loaded in. If not render just default empty JSX.

Related

Uncaught TypeError: Cannot read properties of undefined (reading 'dailyconfirmed')

what's problem with my code i am getting error while accesing mydata.dailyconfirmed after page reloading?
const[state,setState]=useState({});
async function getApiIndia1(){
const temp=await fetch('https://data.covid19india.org/data.json')
const mydata=await temp.json();
setState(mydata)
}
useEffect(() => {
getApiIndia1();
}, [])
You cannot access mydata outside of getApiIndia1 (which I assume you are trying to do). It is only defined in that block, which is the reason why you're using state (essentially to save the required data globally). mydata can't be found and that's why it's throwing an error.
What you should do instead is access state, which is where you're storing that data.
But that will still throw an undefined. That's because of the issue that previous answers have already highlighted. You need to access state.cases_time_series.dailyconfirmed. That should give you the data you want.
It's always a good idea to check API responses carefully. ;)
Update the setState
setState(mydata.cases_time_series)
and when you wish to find dailyconfirmed, loop over your state which is basically an array of object.
state.map((dailyconf)=>{
if(dailyconf?.dailyconfirmed) console.log(dailyconf?.dailyconfirmed)
})

Why does this hook call return undefined when I simply change the variable name?

I'm running an API call via redux - in the tutorial, I am following, they use the variable name "sales" to store the data. Following along, I kept getting undefined, and after some troubleshooting, it appears that the only way for me to get any data out of this API call is to save the result in a variable named exactly "data".
// Correctly retrieves and logs the data
const { data, isFetching } = useGetSalesQuery();
console.log(data);
// Returns "undefined" every time
const { anythingElse, isFetching } = useGetSalesQuery();
console.log(anythingElse);
data is not defined anywhere else within this component. So what's going on here? Was Redux updated to force us to always use the name "data"? This is doing my head in.
useGetSalesQuery returns an object that has data and isFetching. Attempting to access an arbitrary field from that object will get you undefined. What's going on in this component is that you are defining a variable data and assign it the value from the field data that is returned from useGetSalesQuery
See javascript's destructuring assignment

Error in displaying JSON in react

On calling an API , got a response, stored it in a variable "items" and it is getting displayed on console also. When i access items.data[0].id, it is getting displayed in console but when i try to display same thing in render method, error is coming that :-
TypeError : cannot read property 0 of undefined.
I am calling the API call in ComponentWillMount() function in react.
I don't think there is enough context here to answer your question. Can you provide an example? In the meantime, I'll still try to help you.
I am not sure if your request is synchronous or asynchronous. Looking at your error, you are probably making an asynchronous request. When the first render() is called, items hasn't resolved yet. Therefore, item.data is undefined, which is the cause of your error.
A solution is to initialize the data property of this.state.item to an empty array [], that way your not calling the index operator of an undefined object.

Error when trying to access an object inside an array with React

I'm trying to access a property on an array that has on index 0 an object and I'm trying the following: object[0].main But the console throws me an error.
I'm using React on codepen so it doesn't show me the error pretty well, I want to access that property to be able to put it on another object that I'll pass down as props (because is something I hold on my state). Here is my code: https://codepen.io/manAbl/pen/aGymRg?editors=0011 Look for line 56.
This is stressing me out.
Thanks in advance
This happens because the data is not loaded from the server yet so the object will be initially as you set it to {}
so to fix this you can do
instead of
description: this.state.weather.weather[0].main,
do
description: this.state.weather.weather && this.state.weather.weather[0].main,
The idea is you set the initial state to : {} correct? and render is called before the ajax is actually finished since its async.
so on first render it will be "{}" and you are doing [0].main on it. which will crash.

Parsing JSON objects array and displaying it in ReactJS

I've been facing a weird issue lately with my React App. I'm trying to parse a JSON object that contains arrays with data. The data is something like this:
{"Place":"San Francisco","Country":"USA", "Author":{"Name":"xyz", "Title":"View from the stars"}, "Year":"2018", "Places":[{"Price":"Free", "Address":"sfo"},{"Price":"$10","Address":"museum"}] }
The data contains multiple arrays like the Author example I've just shown. I have a function that fetches this data from a URL. I'm calling that function in componentDidMount. The function takes the data i.e responseJson and then stores it in an empty array that I've set called result using setState. In my state I have result as result:[]. My code for this would look something like this:
this.setState({result:responseJson})
Now, when I've been trying to access say Author Name from result I get an error. So something like this:
{this.state.result.Author.Name}
I'm doing this in a function that I'm using to display stuff. I'm calling this function in my return of my render function. I get an error stating :
TypeError:Cannot read property 'Name' of undefined. I get the same error if I try for anything that goes a level below inside. If I display {this.state.result.Place} or {this.state.result.Country} it's all good. But if I try,say {this.state.result.Author.Title} or {this.state.result.Places[0].Price} it gives me the same error.
Surprising thing is I've parsed this same object in a different component of mine and got no errors there. Could anyone please explain me why this is happening?
If I store the individual element while I setState in my fetch call function, I can display it. For example:
{result:responseJson,
AuthorName:responseJson.Author.Name
}
Then I'm able to go ahead and use it as {this.state.AuthorName}.
Please help me find a solution to this problem. Thanks in advance!
It could be that your state object is empty on the first render, and only updated with the data from the API after the request has completed (i.e. after the first render). The Name and Place properties don't throw an error, as they probably resolve to undefined.
Try putting an if block in your render method to check if the results have been loaded, and display a loading indicator if they haven't.
I'm guessing your initial state is something like this:
{ results: {} }
It's difficult to say without seeing more code.
[EDIT]: adding notes from chat
Data isn't available on first render. The sequence of events rendering this component looks something like this:
Instantiate component, the initial state is set to { results: [] }
Component is mounted, API call is triggered (note, this asynchronous, and doesn't return data yet)
Render method is called for the 1st time. This happens BEFORE the data is returned from the API request, so the state object is still {results: [] }. Any attempts to get authors at this point will throw an error as results.Authors is undefined
API request returns data, setState call updates state to { results: { name: 'test', author: [...] } }. This will trigger a re-render of the component
Render method is called for the 2nd time. Only at this point do you have data in the state object.
If this state evolves, means it is changed at componentDidMount, or after a fetch or whatever, chances are that your state is first empty, then it fills with your data.
So the reason you are getting this error, is simply that react tries to get this.state.result.Author.Name before this.state.result.Author even exists.
To get it, first test this.state.result.Author, and if indeed there's something there, then get Author.Name like this.
render(){
return(
<div>
{this.state.result.Author ? this.state.result.Author.Name : 'not ready yet'}
</div>
);
}
[EDIT] I'll answer the comment here:
It's just because they are at a higher level in the object.
this.state.result will always return something, even false if there is no result key in your state (no result key in your constructor for instance when the component mounts).
this.state.result.Country will show the same error if result is not a key of your state in your constructor. However, if result is defined in your constructor, then it will be false at first, then become the data when the new state populates.
this.state.result.Author.Name is again one level deeper...
So to avoid it, you would have to define your whole "schema" in the constructor (bad practice in my opinion). This below would throw no error when getting this.state.result.Author.Name if I'm not mistaken. It would first return false, then the value when available.
constructor(props){
super(props);
this.state={
result: {
Author: {}
}
}
}

Categories

Resources