TypeError: Cannot set property 'setState' of undefined. react - reactjs

I did fetch data from NYTimes API and console log them.
My initial state is {searchResponse: null}
Then set state the response
this.setState=({searchResponse:response.data});
and pass it to another component named listview_component. In that component, I handle the null value of prop.
but the response from the API did not push in searchResponse. and show the error : TypeError: Cannot set property 'setState' of undefined.
How to solve this?
please check out this code
https://github.com/shojibMahabub/news-scroller/tree/develop

this.setState = {user_input} is wrong. setState is a function it should be:
this.setState({user_input});
On top you forgot to bind your function in your constructor:
this.handle_user_input = this.handle_user_input.bind(this);
I could not find any mention of setState=({searchResponse:response.data})in your code, but it probably fails because of the same issue.

If needed to access .this convert the function to fat arrow function.
do_search = (keyword) => {
axios
.get(
url, // takes the variable url
{
params: {
api_key: api_key,
q: keyword
}
}
)
.then(response => {
console.log(response);
this.setState=({searchResponse:response.data});
})
.catch(function(error) {
console.log(error);
});
}

Related

Cannot read property 'setState' of undefined while updating geolocation values

I am trying to get latitude and longitude using geolocation. I got the value, but when I try to set state values, it shows me this error. "Cannot read property 'setState' of undefined". Probably this error comes as I called setState inside another function.
I also tried to make another function for setting state values but it also throws this is not defined error. What is the right way of doing this?
getLocation=()=>
{
navigator.geolocation.getCurrentPosition(function(position) {
this.setState({venueLatitude:position.coords.latitude});
this.setState({venueLongitude:position.coords.longitude});
});
}
this isn't referring to the instance of the component. You can more read about it, example: https://www.andrewconnell.com/blog/deal-with-undefined-this-react-event-handler-performant-way/
getLocation = () => {
navigator.geolocation.getCurrentPosition((position) => {
this.setState({ venueLatitude: position.coords.latitude });
this.setState({ venueLongitude: position.coords.longitude });
});
};

Stuck with: 'Uncaught TypeError: this.state.users.map is not a function' in react (Axios)

I want to make a get request to this dummy endpoint: https://reqres.in/api/users/2
but I constantly get the error message:
TypeError: this.state.users.map is not a function
This is my code:
state = {
users: []
}
componentDidMount() {
axios.get(`https://reqres.in/api/users/2`)
.then(res => {
this.setState({ users : res.data });
})
}
Any help on what I do wrong?
It appears the endpoint is returning an object not an array.
If you wish to use an array you could do this:
this.setState({ users: [res.data] })
But in a nutshell I personally would change this name of state to a singular term. Then use it as an object (as it from the endpoint).
E.g
this.setState({ person: res.data })
Then consume properties as desired:
this.state.person.id
Hope this helps 👍🏻

mapping over items in ajax call react

I am making an ajax call to google fonts api and receiving a list of items from there. I am calling my ajax call inside of my componentDidMount method.
I later have a method that renders a field of options for my fonts that I have received from my ajax request. I am unsure what I am doing incorrectly.
componentDidMount() {
axios.get(URL)
.then((data) => {
console.log("data" + data);
this.setState({
googleFonts: data
})
})
.catch((err) => {
console.log(err);
this.setState({
errors: err
})
})
}
here is where I render my options
renderFonts() {
let data = this.state.googleFonts.data.items;
return data.map((font, index) => {
return (
<option>{font.family}</option>
)
})
}
here is where I call my method that returns the options
<FormControl
style={inputFieldStyle}
componentClass="select"
placeholder="select"
>
{this.renderFonts()}
</FormControl>
the error that I am getting is that data is undefined specifically this.state.googleFonts.data.items. I think it has to do with a race condition of my componentDidMount ajax call and the method being called before that. What am I doing wrong?
It looks like you are trying to access a property that has not been asynchronously fetched yet and getting a Cannot read property of undefined error.
At the very beginning of your renderFonts method, you can add this line:
if (!this.state.googleFonts) return null;
This way, you will not attempt to access properties of this.state.googleFonts before it is defined. After the API call is resolved, the component will be rerendered with the correct values.
Your other option would be to use lodash _.get which returns undefined instead of throwing an error when you attempt to access a property of undefined.

cannot access an array of objects returned from api call in react

I have an API call, that is called multiple times inside a map function to retrieve nested data from mongodb.
The results are pushed to an array.
The array is used as props data for a child component.
I can console.log() the resulting array. but I cannot access it in react, or iterate through it.
Does anyone know how to sort this problem. It should work. I can't see any reason for it not to. It's becoming very frustrating
fetchMemory(props) {
const tempMemories = [];
if (props.journey) {
props.journey.memories.map((mem) = > {
superagent
.get(`/memories/$ {
mem
}`)
.end(function (err, res) {
let tp = res.body
tempMemories.push(tp)
});
})
this.setState({
memories: tempMemories
})
}
}
I cannot access the array of memories returned in setstate. they do show up if you inspect them in the console/ It just returns an error, in the child component (as props).
"TypeError: Cannot read property 'memories' of undefined"
Thanks in advance.
Fetch data via axios is async, so basically tempMemories will be empty in your call to setState(), because the network calls aren't completed yet.
You should use Promise.all like this:
const promiseList = props.journey.memories.map( mem => {
return superagent
.get(`/memories/${mem}`)
.then( res => res.body );
});
Promise.all( promiseList )
.then( results => {
this.setState({
memories: results
});
})
.catch( err => {
...
});
So basically you create one promise for each element and then wait for all of them to get resolved to do the setState() call.

How to Set the response to a state by using this.setState inside a componentDidMount() method

From my react application I made an Ajax request to the spring Mvc controller, got a Jason response from the requested spring controller.
Now am trying to set this response inside my componentDidMont () to a state defined inside the constructor using this.setState method using react js.
When I tried to set the state using this.setState method I get Type Error:
Cannot read property 'set State' of undefined error
Please do help me fix this error.
Course.js
import React from "react";
import Article from "../components/Article";
import axios from 'axios';
export default class Courses extends React.Component {
constructor() {
super();
this.state={items:[]};
}
componentDidMount() {
console.log("hello");
axios.get('http://localhost:8080/ulearn/rest/course/getAll').then(function (response) {
this.setState({items: response});
console.log(response);
}).catch(function (error) {
console.log(error);
});
}
Render method
render() {
return (
<div>
<div>Response - {this.state.items}</div>;
</div>
);
} }
Below is the error message:
In Javascript, defining an anonymous function does not automatically inherit the this context from the upper scope. So when you define an anonymous function callback for your ajax request, this becomes undefined inside it. Since you are already using ES6 features (like import and class) you can also use arrow functions with => to overcome the issue. They behave like normal functions, but do not create a new this context. So you can simply do this in your componentDidMount:
axios.get('http://localhost:8080/ulearn/rest/course/getAll')
.then((response) => {
this.setState({items: response});
console.log(response);
}).catch((error) => {
console.log(error);
});
As per the error in your comment, as the response above mine beat me to answering your question :) -
You are trying to print out the entire object, try printing out each item individually or adding .toString() behind this.state.items in your render method. The same thing happens when you try to print new Date() for example, it won't let you print out the entire object, but it will let you print a string representation of the object, so new Date().toString() would work for example.

Resources