Error in displaying JSON in react - javascript

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.

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

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

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.

Passing props and mapping data in React

I'm working on a project that requires me to pass data to two functional components.
My axios call to the API seems to work, as well as setting the state with hooks, but I keep receiving these two errors:
Error Cannot convert undefined or null to object I tried checking if the array is empty but that didn't seem to solve the problem
summaryMetrics is not defined - This I don't understand because summartMetrics is defined. Could it be that the elements are being displayed before the data is fetched ?
Here are the files in a codesandbox
Included the API's so people can see the structure of how the JSON is being returned.
Im not sure if I'm passing and mapping the data correctly.
Here are the files in a codesandbox
Any help is very much appreciated
Since your state has this form :
const [summary, setSummaryData] = useState({
summaryMetrics: null,
platformsData: null
});
...you should access your state like this :
<SummaryMetrics
uniqueSocialMediaPost={summary.summaryMetrics[0]["uniqueSocialMediaPost"]}
positiveScore={summary.summaryMetrics[0]["positiveScore"]}
riskScore={summary.summaryMetrics[0]["riskScore"]}
/>
[...]
Note the "summary." before "summaryMetrics" :
summary.summaryMetrics[0]["uniqueSocialMediaPost"]
Fixed Fixed Code Sandbox (other things seems to go wrong though, white screen, but syntax error is fixed) :
Previous errors were :
mocky.io serves content over HTTP, Code Sandbox over HTTPS so mixed content issue : Chrome does not allow this kind of mix in protocols, fixed by using HTTPS protocol to grab infos from mocky.io,
no unique keys for SummaryByPlatform component in map function
Chrome dev tools is your friend when nothing happens as expected :).
By the way you could just
summary.summaryMetrics.map(s => <SummaryByPlatform summaryMetrics={s} />)
...instead of gettings keys, and you could simply pass whole summaryMetrics object to SummaryByPlatform and have only one props. But that's another subject.
Good luck with it.
Your issue is that you're not waiting for summaryMetrics to load. It's trying to read the array before it's been fetched.
What I would do, is put the render inside a function and conditionally load it once the data is available.
So your Summary.js file would look like this:
const renderSummaryMetrics = () =>
summary &&
summary.summaryMetrics && (
<div>
<SummaryMetrics
uniqueSocialMediaPost={summary.summaryMetrics[0]["uniqueSocialMediaPost"]}
positiveScore={summary.summaryMetrics[0]["positiveScore"]}
riskScore={summary.summaryMetrics[0]["riskScore"]}
/>
{Object.keys(summary.summaryMetrics) &&
Object.keys(summary.summaryMetrics).length > 0
? Object.keys(summary.summaryMetrics).map(keyName => (
<SummaryByPlatform
platform={keyName}
mean_sentiment={summary.summaryMetrics[keyName].mean_sentiment}
post_count={summary.summaryMetrics[keyName].post_count}
positive_posts={summary.summaryMetrics[keyName].positive_posts}
negative_posts={summary.summaryMetrics[keyName].negative_posts}
/>
))
: null}
</div>);
return renderSummaryMetrics();
There are several problems:
summaryMetrics is indeed not defined. It was actually defined as summary.summaryMetrics.
summary.summaryMetrics[0][...] will cause another "undefined error", because it was defined with default value of null.
Explanation for Problem 1:
No further explanation needed.
Explanation for Problem 2:
useEffect in React functional component will only be run after the component is being rendered.
This means that when you execute summary.summaryMetrics[0][...], summary.summaryMetrics is actually null because you defined it as the default value. Therefore, the steps behind will generate another error because null[0] is not possible.
What you need to do is to check whether each object properties down the tree is actually a valid object before you call the property. Otherwise, the error will happen down the property tree.
I can't show you how to correct your code, because I would need to change a big part of you code. What you can try is to mainly check the presence of values of summary.summaryMetrics first, before calling it's children properties.

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