ReactJS: get data from api and map data












1















I am learning ReactJS. In my program, I am making an API call and later mapping it.
The data which is fetched by API call is like,
data = [{"uid":"1", "title":"hello"},{"uid":"2", "title":"World"}]



import ImporterAPI from '../api';
const API = new ImporterAPI();

class Home extends Component {
constructor(props) {
super(props);
this.state = {
data: ''
}}

componentWillMount() {
this.setState({ data: API.getData()}, () => {
console.log("data fetched");
var mapData =
this.state.data.map( (object, i) => {
mapData.push(<p key={i}>{object}</p>)
})
})
}

render() {
return (
<div className="home">
{this.mapData}
</div>
)
}
}


And my API file,



import axios from 'axios';
class API {
getData = () => {
axios.get('http://localhost:8005/data')
.then(function (response) {
if (response.status === 200 && response != null) {
var data = response.data;
console.log(data)
return data
} else {
console.log('problem');
}
})
.catch(function (error) {
console.log(error);
});
}
}


My console.log is printing the data from API call and then I'm returning the data. Where in home component data is assigned using setState. But there is no data storing into this.state.data. It always remains undefined and I got error "TypeError: Cannot read property 'map' of undefined".



Please guide me. How should I print API call data & I would also like to know if this program is good or bad in terms of performance for making API calls or any other better way to improve performance. Thanks.



I would appreciate help.










share|improve this question























  • You missed the return before axios. Just add return in front of axios like this return axios , it will work.

    – kumar k
    Nov 18 '18 at 5:30













  • I think the response is a JSON object and so the map function will not work. Can you please post your sample response data here?

    – kumar k
    Nov 18 '18 at 6:25











  • @kumark ... my console print response data -> (2) [ 0:{"uid":"1", "title":"hello"} 1: {"uid":"2", "title":"World"}]

    – TEMP
    Nov 18 '18 at 6:36


















1















I am learning ReactJS. In my program, I am making an API call and later mapping it.
The data which is fetched by API call is like,
data = [{"uid":"1", "title":"hello"},{"uid":"2", "title":"World"}]



import ImporterAPI from '../api';
const API = new ImporterAPI();

class Home extends Component {
constructor(props) {
super(props);
this.state = {
data: ''
}}

componentWillMount() {
this.setState({ data: API.getData()}, () => {
console.log("data fetched");
var mapData =
this.state.data.map( (object, i) => {
mapData.push(<p key={i}>{object}</p>)
})
})
}

render() {
return (
<div className="home">
{this.mapData}
</div>
)
}
}


And my API file,



import axios from 'axios';
class API {
getData = () => {
axios.get('http://localhost:8005/data')
.then(function (response) {
if (response.status === 200 && response != null) {
var data = response.data;
console.log(data)
return data
} else {
console.log('problem');
}
})
.catch(function (error) {
console.log(error);
});
}
}


My console.log is printing the data from API call and then I'm returning the data. Where in home component data is assigned using setState. But there is no data storing into this.state.data. It always remains undefined and I got error "TypeError: Cannot read property 'map' of undefined".



Please guide me. How should I print API call data & I would also like to know if this program is good or bad in terms of performance for making API calls or any other better way to improve performance. Thanks.



I would appreciate help.










share|improve this question























  • You missed the return before axios. Just add return in front of axios like this return axios , it will work.

    – kumar k
    Nov 18 '18 at 5:30













  • I think the response is a JSON object and so the map function will not work. Can you please post your sample response data here?

    – kumar k
    Nov 18 '18 at 6:25











  • @kumark ... my console print response data -> (2) [ 0:{"uid":"1", "title":"hello"} 1: {"uid":"2", "title":"World"}]

    – TEMP
    Nov 18 '18 at 6:36
















1












1








1








I am learning ReactJS. In my program, I am making an API call and later mapping it.
The data which is fetched by API call is like,
data = [{"uid":"1", "title":"hello"},{"uid":"2", "title":"World"}]



import ImporterAPI from '../api';
const API = new ImporterAPI();

class Home extends Component {
constructor(props) {
super(props);
this.state = {
data: ''
}}

componentWillMount() {
this.setState({ data: API.getData()}, () => {
console.log("data fetched");
var mapData =
this.state.data.map( (object, i) => {
mapData.push(<p key={i}>{object}</p>)
})
})
}

render() {
return (
<div className="home">
{this.mapData}
</div>
)
}
}


And my API file,



import axios from 'axios';
class API {
getData = () => {
axios.get('http://localhost:8005/data')
.then(function (response) {
if (response.status === 200 && response != null) {
var data = response.data;
console.log(data)
return data
} else {
console.log('problem');
}
})
.catch(function (error) {
console.log(error);
});
}
}


My console.log is printing the data from API call and then I'm returning the data. Where in home component data is assigned using setState. But there is no data storing into this.state.data. It always remains undefined and I got error "TypeError: Cannot read property 'map' of undefined".



Please guide me. How should I print API call data & I would also like to know if this program is good or bad in terms of performance for making API calls or any other better way to improve performance. Thanks.



I would appreciate help.










share|improve this question














I am learning ReactJS. In my program, I am making an API call and later mapping it.
The data which is fetched by API call is like,
data = [{"uid":"1", "title":"hello"},{"uid":"2", "title":"World"}]



import ImporterAPI from '../api';
const API = new ImporterAPI();

class Home extends Component {
constructor(props) {
super(props);
this.state = {
data: ''
}}

componentWillMount() {
this.setState({ data: API.getData()}, () => {
console.log("data fetched");
var mapData =
this.state.data.map( (object, i) => {
mapData.push(<p key={i}>{object}</p>)
})
})
}

render() {
return (
<div className="home">
{this.mapData}
</div>
)
}
}


And my API file,



import axios from 'axios';
class API {
getData = () => {
axios.get('http://localhost:8005/data')
.then(function (response) {
if (response.status === 200 && response != null) {
var data = response.data;
console.log(data)
return data
} else {
console.log('problem');
}
})
.catch(function (error) {
console.log(error);
});
}
}


My console.log is printing the data from API call and then I'm returning the data. Where in home component data is assigned using setState. But there is no data storing into this.state.data. It always remains undefined and I got error "TypeError: Cannot read property 'map' of undefined".



Please guide me. How should I print API call data & I would also like to know if this program is good or bad in terms of performance for making API calls or any other better way to improve performance. Thanks.



I would appreciate help.







reactjs






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 18 '18 at 5:25









TEMPTEMP

599




599













  • You missed the return before axios. Just add return in front of axios like this return axios , it will work.

    – kumar k
    Nov 18 '18 at 5:30













  • I think the response is a JSON object and so the map function will not work. Can you please post your sample response data here?

    – kumar k
    Nov 18 '18 at 6:25











  • @kumark ... my console print response data -> (2) [ 0:{"uid":"1", "title":"hello"} 1: {"uid":"2", "title":"World"}]

    – TEMP
    Nov 18 '18 at 6:36





















  • You missed the return before axios. Just add return in front of axios like this return axios , it will work.

    – kumar k
    Nov 18 '18 at 5:30













  • I think the response is a JSON object and so the map function will not work. Can you please post your sample response data here?

    – kumar k
    Nov 18 '18 at 6:25











  • @kumark ... my console print response data -> (2) [ 0:{"uid":"1", "title":"hello"} 1: {"uid":"2", "title":"World"}]

    – TEMP
    Nov 18 '18 at 6:36



















You missed the return before axios. Just add return in front of axios like this return axios , it will work.

– kumar k
Nov 18 '18 at 5:30







You missed the return before axios. Just add return in front of axios like this return axios , it will work.

– kumar k
Nov 18 '18 at 5:30















I think the response is a JSON object and so the map function will not work. Can you please post your sample response data here?

– kumar k
Nov 18 '18 at 6:25





I think the response is a JSON object and so the map function will not work. Can you please post your sample response data here?

– kumar k
Nov 18 '18 at 6:25













@kumark ... my console print response data -> (2) [ 0:{"uid":"1", "title":"hello"} 1: {"uid":"2", "title":"World"}]

– TEMP
Nov 18 '18 at 6:36







@kumark ... my console print response data -> (2) [ 0:{"uid":"1", "title":"hello"} 1: {"uid":"2", "title":"World"}]

– TEMP
Nov 18 '18 at 6:36














2 Answers
2






active

oldest

votes


















1














There're two problems in your code.



First, API.getData() is an async function. It means when you call API.getData(), the data is not return intermediately (think like it takes few milliseconds to get the data). You should setState after you fetched the data.



Secondly, you should send render logic in render function.



It should look like this:



import React, { Component } from 'react'
import ImporterAPI from '../api'
const API = new ImporterAPI()

class Home extends Component {
constructor(props) {
super(props)
this.state = {
data:
}
}

componentWillMount() {
API.getData().then(response => {
console.log('Data fetched', response)
this.setState({
data: response
})
})
}

render() {
return (
<div className="home">
{this.state.data.map((object, index) => (
<p key={index}>{object}</p>
))}
</div>
)
}
}


As @Askiron answer, you also should return axios.... in your API function.



Edit 2: Here's the better API, which return data in error case, so you don't get this.state.data is not a function:



import axios from 'axios'

class API {
getData = () => {
return axios
.get('http://localhost:8005/data')
.then(function(response) {
if (response.status === 200 && response != null) {
var data = response.data
return data
} else {
throw new Error('Empty data')
}
})
.catch(function(error) {
console.log(error)
return // Return empty array in case error response.
})
}
}





share|improve this answer


























  • Thanks for replying :) .... After following your steps I'm getting this error "TypeError: this.state.data.map is not a function" and in the API component console.log is printing data twice ...similarly console.log is printing data twice in Home component.

    – TEMP
    Nov 18 '18 at 6:10











  • Sorry. You should init your data state to empty array at first. I edited my code. Check it out!

    – MiraiHanabi
    Nov 18 '18 at 6:34











  • And in the API, you should return data in error cases. Think API.getData() is like a function, get input and return output. In case of error, you seem not return any data. I will update my answer to hope you can understand more, can resolve all your problems.

    – MiraiHanabi
    Nov 18 '18 at 6:36











  • And your console print data twice, is because one print in API.getData(), one print in your React Component when you fetch data. So I delete the console.log in API.getData().

    – MiraiHanabi
    Nov 18 '18 at 6:42











  • I'm getting same error at Home.render ... "TypeError: Cannot read property 'map' of undefined"

    – TEMP
    Nov 18 '18 at 6:55



















0














Do you really need another class for getting api data? Not required



Also componentWillMount method is deprecated so I would recommend you to move your axios code to componentDidMount method within the class.



Also initialize the data with empty array instead of string. And set the api response data to state i.e., data



Do map directly in render and display data.



Use arrow function in axios .then and .catch like I did in the below code otherwise this won’t be available to access state or props. You need to bind every .then and .catch otherwise



Your code can be simplified something like below



     class Home extends Component {
constructor(props) {
super(props);
this.state = {
data:
}
}

componentDidMount() {
axios.get('http://localhost:8005/data')
.then(response => {
if (response.status === 200 && response != null) {
this.setState({
data: response.data
});
} else {
console.log('problem');
}
})
.catch(error => {
console.log(error);
});
}

render() {
const { data } = this.state;
return (
<div className="home">
{Array.isArray(data) && data.map(object => (
<p key={object.uid}>{object.title}</p>
))}
</div>
)
}
}





share|improve this answer


























  • :) I am getting this error "TypeError: data.map is not a function"

    – TEMP
    Nov 18 '18 at 6:18











  • I updated my answer. Please give a try now. But Make sure the api returns the data i.e., console.log(response.data); should print array of objects in axios success response

    – Hemadri Dasari
    Nov 18 '18 at 6:31













  • I'm getting "localhost:8005/data" 404 not found and another error request failed. But before this error I'm getting Map error "Uncaught TypeError: data.map is not a function".

    – TEMP
    Nov 18 '18 at 6:33











  • That means the api url is incorrect. Check your backend api path. If you provide right path to axios.get then the code would work as expected

    – Hemadri Dasari
    Nov 18 '18 at 6:35











  • I fixed it and got .... "Uncaught (in promise) TypeError: res.json is not a function"

    – TEMP
    Nov 18 '18 at 6:43











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53358155%2freactjs-get-data-from-api-and-map-data%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














There're two problems in your code.



First, API.getData() is an async function. It means when you call API.getData(), the data is not return intermediately (think like it takes few milliseconds to get the data). You should setState after you fetched the data.



Secondly, you should send render logic in render function.



It should look like this:



import React, { Component } from 'react'
import ImporterAPI from '../api'
const API = new ImporterAPI()

class Home extends Component {
constructor(props) {
super(props)
this.state = {
data:
}
}

componentWillMount() {
API.getData().then(response => {
console.log('Data fetched', response)
this.setState({
data: response
})
})
}

render() {
return (
<div className="home">
{this.state.data.map((object, index) => (
<p key={index}>{object}</p>
))}
</div>
)
}
}


As @Askiron answer, you also should return axios.... in your API function.



Edit 2: Here's the better API, which return data in error case, so you don't get this.state.data is not a function:



import axios from 'axios'

class API {
getData = () => {
return axios
.get('http://localhost:8005/data')
.then(function(response) {
if (response.status === 200 && response != null) {
var data = response.data
return data
} else {
throw new Error('Empty data')
}
})
.catch(function(error) {
console.log(error)
return // Return empty array in case error response.
})
}
}





share|improve this answer


























  • Thanks for replying :) .... After following your steps I'm getting this error "TypeError: this.state.data.map is not a function" and in the API component console.log is printing data twice ...similarly console.log is printing data twice in Home component.

    – TEMP
    Nov 18 '18 at 6:10











  • Sorry. You should init your data state to empty array at first. I edited my code. Check it out!

    – MiraiHanabi
    Nov 18 '18 at 6:34











  • And in the API, you should return data in error cases. Think API.getData() is like a function, get input and return output. In case of error, you seem not return any data. I will update my answer to hope you can understand more, can resolve all your problems.

    – MiraiHanabi
    Nov 18 '18 at 6:36











  • And your console print data twice, is because one print in API.getData(), one print in your React Component when you fetch data. So I delete the console.log in API.getData().

    – MiraiHanabi
    Nov 18 '18 at 6:42











  • I'm getting same error at Home.render ... "TypeError: Cannot read property 'map' of undefined"

    – TEMP
    Nov 18 '18 at 6:55
















1














There're two problems in your code.



First, API.getData() is an async function. It means when you call API.getData(), the data is not return intermediately (think like it takes few milliseconds to get the data). You should setState after you fetched the data.



Secondly, you should send render logic in render function.



It should look like this:



import React, { Component } from 'react'
import ImporterAPI from '../api'
const API = new ImporterAPI()

class Home extends Component {
constructor(props) {
super(props)
this.state = {
data:
}
}

componentWillMount() {
API.getData().then(response => {
console.log('Data fetched', response)
this.setState({
data: response
})
})
}

render() {
return (
<div className="home">
{this.state.data.map((object, index) => (
<p key={index}>{object}</p>
))}
</div>
)
}
}


As @Askiron answer, you also should return axios.... in your API function.



Edit 2: Here's the better API, which return data in error case, so you don't get this.state.data is not a function:



import axios from 'axios'

class API {
getData = () => {
return axios
.get('http://localhost:8005/data')
.then(function(response) {
if (response.status === 200 && response != null) {
var data = response.data
return data
} else {
throw new Error('Empty data')
}
})
.catch(function(error) {
console.log(error)
return // Return empty array in case error response.
})
}
}





share|improve this answer


























  • Thanks for replying :) .... After following your steps I'm getting this error "TypeError: this.state.data.map is not a function" and in the API component console.log is printing data twice ...similarly console.log is printing data twice in Home component.

    – TEMP
    Nov 18 '18 at 6:10











  • Sorry. You should init your data state to empty array at first. I edited my code. Check it out!

    – MiraiHanabi
    Nov 18 '18 at 6:34











  • And in the API, you should return data in error cases. Think API.getData() is like a function, get input and return output. In case of error, you seem not return any data. I will update my answer to hope you can understand more, can resolve all your problems.

    – MiraiHanabi
    Nov 18 '18 at 6:36











  • And your console print data twice, is because one print in API.getData(), one print in your React Component when you fetch data. So I delete the console.log in API.getData().

    – MiraiHanabi
    Nov 18 '18 at 6:42











  • I'm getting same error at Home.render ... "TypeError: Cannot read property 'map' of undefined"

    – TEMP
    Nov 18 '18 at 6:55














1












1








1







There're two problems in your code.



First, API.getData() is an async function. It means when you call API.getData(), the data is not return intermediately (think like it takes few milliseconds to get the data). You should setState after you fetched the data.



Secondly, you should send render logic in render function.



It should look like this:



import React, { Component } from 'react'
import ImporterAPI from '../api'
const API = new ImporterAPI()

class Home extends Component {
constructor(props) {
super(props)
this.state = {
data:
}
}

componentWillMount() {
API.getData().then(response => {
console.log('Data fetched', response)
this.setState({
data: response
})
})
}

render() {
return (
<div className="home">
{this.state.data.map((object, index) => (
<p key={index}>{object}</p>
))}
</div>
)
}
}


As @Askiron answer, you also should return axios.... in your API function.



Edit 2: Here's the better API, which return data in error case, so you don't get this.state.data is not a function:



import axios from 'axios'

class API {
getData = () => {
return axios
.get('http://localhost:8005/data')
.then(function(response) {
if (response.status === 200 && response != null) {
var data = response.data
return data
} else {
throw new Error('Empty data')
}
})
.catch(function(error) {
console.log(error)
return // Return empty array in case error response.
})
}
}





share|improve this answer















There're two problems in your code.



First, API.getData() is an async function. It means when you call API.getData(), the data is not return intermediately (think like it takes few milliseconds to get the data). You should setState after you fetched the data.



Secondly, you should send render logic in render function.



It should look like this:



import React, { Component } from 'react'
import ImporterAPI from '../api'
const API = new ImporterAPI()

class Home extends Component {
constructor(props) {
super(props)
this.state = {
data:
}
}

componentWillMount() {
API.getData().then(response => {
console.log('Data fetched', response)
this.setState({
data: response
})
})
}

render() {
return (
<div className="home">
{this.state.data.map((object, index) => (
<p key={index}>{object}</p>
))}
</div>
)
}
}


As @Askiron answer, you also should return axios.... in your API function.



Edit 2: Here's the better API, which return data in error case, so you don't get this.state.data is not a function:



import axios from 'axios'

class API {
getData = () => {
return axios
.get('http://localhost:8005/data')
.then(function(response) {
if (response.status === 200 && response != null) {
var data = response.data
return data
} else {
throw new Error('Empty data')
}
})
.catch(function(error) {
console.log(error)
return // Return empty array in case error response.
})
}
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 18 '18 at 6:40

























answered Nov 18 '18 at 5:46









MiraiHanabiMiraiHanabi

129128




129128













  • Thanks for replying :) .... After following your steps I'm getting this error "TypeError: this.state.data.map is not a function" and in the API component console.log is printing data twice ...similarly console.log is printing data twice in Home component.

    – TEMP
    Nov 18 '18 at 6:10











  • Sorry. You should init your data state to empty array at first. I edited my code. Check it out!

    – MiraiHanabi
    Nov 18 '18 at 6:34











  • And in the API, you should return data in error cases. Think API.getData() is like a function, get input and return output. In case of error, you seem not return any data. I will update my answer to hope you can understand more, can resolve all your problems.

    – MiraiHanabi
    Nov 18 '18 at 6:36











  • And your console print data twice, is because one print in API.getData(), one print in your React Component when you fetch data. So I delete the console.log in API.getData().

    – MiraiHanabi
    Nov 18 '18 at 6:42











  • I'm getting same error at Home.render ... "TypeError: Cannot read property 'map' of undefined"

    – TEMP
    Nov 18 '18 at 6:55



















  • Thanks for replying :) .... After following your steps I'm getting this error "TypeError: this.state.data.map is not a function" and in the API component console.log is printing data twice ...similarly console.log is printing data twice in Home component.

    – TEMP
    Nov 18 '18 at 6:10











  • Sorry. You should init your data state to empty array at first. I edited my code. Check it out!

    – MiraiHanabi
    Nov 18 '18 at 6:34











  • And in the API, you should return data in error cases. Think API.getData() is like a function, get input and return output. In case of error, you seem not return any data. I will update my answer to hope you can understand more, can resolve all your problems.

    – MiraiHanabi
    Nov 18 '18 at 6:36











  • And your console print data twice, is because one print in API.getData(), one print in your React Component when you fetch data. So I delete the console.log in API.getData().

    – MiraiHanabi
    Nov 18 '18 at 6:42











  • I'm getting same error at Home.render ... "TypeError: Cannot read property 'map' of undefined"

    – TEMP
    Nov 18 '18 at 6:55

















Thanks for replying :) .... After following your steps I'm getting this error "TypeError: this.state.data.map is not a function" and in the API component console.log is printing data twice ...similarly console.log is printing data twice in Home component.

– TEMP
Nov 18 '18 at 6:10





Thanks for replying :) .... After following your steps I'm getting this error "TypeError: this.state.data.map is not a function" and in the API component console.log is printing data twice ...similarly console.log is printing data twice in Home component.

– TEMP
Nov 18 '18 at 6:10













Sorry. You should init your data state to empty array at first. I edited my code. Check it out!

– MiraiHanabi
Nov 18 '18 at 6:34





Sorry. You should init your data state to empty array at first. I edited my code. Check it out!

– MiraiHanabi
Nov 18 '18 at 6:34













And in the API, you should return data in error cases. Think API.getData() is like a function, get input and return output. In case of error, you seem not return any data. I will update my answer to hope you can understand more, can resolve all your problems.

– MiraiHanabi
Nov 18 '18 at 6:36





And in the API, you should return data in error cases. Think API.getData() is like a function, get input and return output. In case of error, you seem not return any data. I will update my answer to hope you can understand more, can resolve all your problems.

– MiraiHanabi
Nov 18 '18 at 6:36













And your console print data twice, is because one print in API.getData(), one print in your React Component when you fetch data. So I delete the console.log in API.getData().

– MiraiHanabi
Nov 18 '18 at 6:42





And your console print data twice, is because one print in API.getData(), one print in your React Component when you fetch data. So I delete the console.log in API.getData().

– MiraiHanabi
Nov 18 '18 at 6:42













I'm getting same error at Home.render ... "TypeError: Cannot read property 'map' of undefined"

– TEMP
Nov 18 '18 at 6:55





I'm getting same error at Home.render ... "TypeError: Cannot read property 'map' of undefined"

– TEMP
Nov 18 '18 at 6:55













0














Do you really need another class for getting api data? Not required



Also componentWillMount method is deprecated so I would recommend you to move your axios code to componentDidMount method within the class.



Also initialize the data with empty array instead of string. And set the api response data to state i.e., data



Do map directly in render and display data.



Use arrow function in axios .then and .catch like I did in the below code otherwise this won’t be available to access state or props. You need to bind every .then and .catch otherwise



Your code can be simplified something like below



     class Home extends Component {
constructor(props) {
super(props);
this.state = {
data:
}
}

componentDidMount() {
axios.get('http://localhost:8005/data')
.then(response => {
if (response.status === 200 && response != null) {
this.setState({
data: response.data
});
} else {
console.log('problem');
}
})
.catch(error => {
console.log(error);
});
}

render() {
const { data } = this.state;
return (
<div className="home">
{Array.isArray(data) && data.map(object => (
<p key={object.uid}>{object.title}</p>
))}
</div>
)
}
}





share|improve this answer


























  • :) I am getting this error "TypeError: data.map is not a function"

    – TEMP
    Nov 18 '18 at 6:18











  • I updated my answer. Please give a try now. But Make sure the api returns the data i.e., console.log(response.data); should print array of objects in axios success response

    – Hemadri Dasari
    Nov 18 '18 at 6:31













  • I'm getting "localhost:8005/data" 404 not found and another error request failed. But before this error I'm getting Map error "Uncaught TypeError: data.map is not a function".

    – TEMP
    Nov 18 '18 at 6:33











  • That means the api url is incorrect. Check your backend api path. If you provide right path to axios.get then the code would work as expected

    – Hemadri Dasari
    Nov 18 '18 at 6:35











  • I fixed it and got .... "Uncaught (in promise) TypeError: res.json is not a function"

    – TEMP
    Nov 18 '18 at 6:43
















0














Do you really need another class for getting api data? Not required



Also componentWillMount method is deprecated so I would recommend you to move your axios code to componentDidMount method within the class.



Also initialize the data with empty array instead of string. And set the api response data to state i.e., data



Do map directly in render and display data.



Use arrow function in axios .then and .catch like I did in the below code otherwise this won’t be available to access state or props. You need to bind every .then and .catch otherwise



Your code can be simplified something like below



     class Home extends Component {
constructor(props) {
super(props);
this.state = {
data:
}
}

componentDidMount() {
axios.get('http://localhost:8005/data')
.then(response => {
if (response.status === 200 && response != null) {
this.setState({
data: response.data
});
} else {
console.log('problem');
}
})
.catch(error => {
console.log(error);
});
}

render() {
const { data } = this.state;
return (
<div className="home">
{Array.isArray(data) && data.map(object => (
<p key={object.uid}>{object.title}</p>
))}
</div>
)
}
}





share|improve this answer


























  • :) I am getting this error "TypeError: data.map is not a function"

    – TEMP
    Nov 18 '18 at 6:18











  • I updated my answer. Please give a try now. But Make sure the api returns the data i.e., console.log(response.data); should print array of objects in axios success response

    – Hemadri Dasari
    Nov 18 '18 at 6:31













  • I'm getting "localhost:8005/data" 404 not found and another error request failed. But before this error I'm getting Map error "Uncaught TypeError: data.map is not a function".

    – TEMP
    Nov 18 '18 at 6:33











  • That means the api url is incorrect. Check your backend api path. If you provide right path to axios.get then the code would work as expected

    – Hemadri Dasari
    Nov 18 '18 at 6:35











  • I fixed it and got .... "Uncaught (in promise) TypeError: res.json is not a function"

    – TEMP
    Nov 18 '18 at 6:43














0












0








0







Do you really need another class for getting api data? Not required



Also componentWillMount method is deprecated so I would recommend you to move your axios code to componentDidMount method within the class.



Also initialize the data with empty array instead of string. And set the api response data to state i.e., data



Do map directly in render and display data.



Use arrow function in axios .then and .catch like I did in the below code otherwise this won’t be available to access state or props. You need to bind every .then and .catch otherwise



Your code can be simplified something like below



     class Home extends Component {
constructor(props) {
super(props);
this.state = {
data:
}
}

componentDidMount() {
axios.get('http://localhost:8005/data')
.then(response => {
if (response.status === 200 && response != null) {
this.setState({
data: response.data
});
} else {
console.log('problem');
}
})
.catch(error => {
console.log(error);
});
}

render() {
const { data } = this.state;
return (
<div className="home">
{Array.isArray(data) && data.map(object => (
<p key={object.uid}>{object.title}</p>
))}
</div>
)
}
}





share|improve this answer















Do you really need another class for getting api data? Not required



Also componentWillMount method is deprecated so I would recommend you to move your axios code to componentDidMount method within the class.



Also initialize the data with empty array instead of string. And set the api response data to state i.e., data



Do map directly in render and display data.



Use arrow function in axios .then and .catch like I did in the below code otherwise this won’t be available to access state or props. You need to bind every .then and .catch otherwise



Your code can be simplified something like below



     class Home extends Component {
constructor(props) {
super(props);
this.state = {
data:
}
}

componentDidMount() {
axios.get('http://localhost:8005/data')
.then(response => {
if (response.status === 200 && response != null) {
this.setState({
data: response.data
});
} else {
console.log('problem');
}
})
.catch(error => {
console.log(error);
});
}

render() {
const { data } = this.state;
return (
<div className="home">
{Array.isArray(data) && data.map(object => (
<p key={object.uid}>{object.title}</p>
))}
</div>
)
}
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 18 '18 at 6:47

























answered Nov 18 '18 at 6:05









Hemadri DasariHemadri Dasari

8,82021540




8,82021540













  • :) I am getting this error "TypeError: data.map is not a function"

    – TEMP
    Nov 18 '18 at 6:18











  • I updated my answer. Please give a try now. But Make sure the api returns the data i.e., console.log(response.data); should print array of objects in axios success response

    – Hemadri Dasari
    Nov 18 '18 at 6:31













  • I'm getting "localhost:8005/data" 404 not found and another error request failed. But before this error I'm getting Map error "Uncaught TypeError: data.map is not a function".

    – TEMP
    Nov 18 '18 at 6:33











  • That means the api url is incorrect. Check your backend api path. If you provide right path to axios.get then the code would work as expected

    – Hemadri Dasari
    Nov 18 '18 at 6:35











  • I fixed it and got .... "Uncaught (in promise) TypeError: res.json is not a function"

    – TEMP
    Nov 18 '18 at 6:43



















  • :) I am getting this error "TypeError: data.map is not a function"

    – TEMP
    Nov 18 '18 at 6:18











  • I updated my answer. Please give a try now. But Make sure the api returns the data i.e., console.log(response.data); should print array of objects in axios success response

    – Hemadri Dasari
    Nov 18 '18 at 6:31













  • I'm getting "localhost:8005/data" 404 not found and another error request failed. But before this error I'm getting Map error "Uncaught TypeError: data.map is not a function".

    – TEMP
    Nov 18 '18 at 6:33











  • That means the api url is incorrect. Check your backend api path. If you provide right path to axios.get then the code would work as expected

    – Hemadri Dasari
    Nov 18 '18 at 6:35











  • I fixed it and got .... "Uncaught (in promise) TypeError: res.json is not a function"

    – TEMP
    Nov 18 '18 at 6:43

















:) I am getting this error "TypeError: data.map is not a function"

– TEMP
Nov 18 '18 at 6:18





:) I am getting this error "TypeError: data.map is not a function"

– TEMP
Nov 18 '18 at 6:18













I updated my answer. Please give a try now. But Make sure the api returns the data i.e., console.log(response.data); should print array of objects in axios success response

– Hemadri Dasari
Nov 18 '18 at 6:31







I updated my answer. Please give a try now. But Make sure the api returns the data i.e., console.log(response.data); should print array of objects in axios success response

– Hemadri Dasari
Nov 18 '18 at 6:31















I'm getting "localhost:8005/data" 404 not found and another error request failed. But before this error I'm getting Map error "Uncaught TypeError: data.map is not a function".

– TEMP
Nov 18 '18 at 6:33





I'm getting "localhost:8005/data" 404 not found and another error request failed. But before this error I'm getting Map error "Uncaught TypeError: data.map is not a function".

– TEMP
Nov 18 '18 at 6:33













That means the api url is incorrect. Check your backend api path. If you provide right path to axios.get then the code would work as expected

– Hemadri Dasari
Nov 18 '18 at 6:35





That means the api url is incorrect. Check your backend api path. If you provide right path to axios.get then the code would work as expected

– Hemadri Dasari
Nov 18 '18 at 6:35













I fixed it and got .... "Uncaught (in promise) TypeError: res.json is not a function"

– TEMP
Nov 18 '18 at 6:43





I fixed it and got .... "Uncaught (in promise) TypeError: res.json is not a function"

– TEMP
Nov 18 '18 at 6:43


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53358155%2freactjs-get-data-from-api-and-map-data%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Tangent Lines Diagram Along Smooth Curve

Yusuf al-Mu'taman ibn Hud

Zucchini