i'm working with react to plete the front end of a rest application.
I have json being sent to the front end, and I use fetch .
fetch('/task')
.then(function(data) {
return data.json();
})
.then(function(json) {
json.tasks.forEach(function(task) {
console.log(task.name)
})
});
So i'm able to console.log each task.name, but where to now? How do I get my ponent to display each task as a
?
Basically, where in a ponent does this type of logic go? Do i save the fetch request to a variable and then setState = variable?
this is my ponent:
class Task extends React.Component {
render() {
return <p> hey </p>
}
}
i'm working with react to plete the front end of a rest application.
I have json being sent to the front end, and I use fetch .
fetch('/task')
.then(function(data) {
return data.json();
})
.then(function(json) {
json.tasks.forEach(function(task) {
console.log(task.name)
})
});
So i'm able to console.log each task.name, but where to now? How do I get my ponent to display each task as a
?
Basically, where in a ponent does this type of logic go? Do i save the fetch request to a variable and then setState = variable?
this is my ponent:
class Task extends React.Component {
render() {
return <p> hey </p>
}
}
Share
Improve this question
asked Apr 20, 2017 at 23:33
Steve NovoselSteve Novosel
352 silver badges6 bronze badges
1
- setState is probably the best approach. – A. L Commented Apr 20, 2017 at 23:44
1 Answer
Reset to default 3You need to initialize a state object, which you can update when the fetch is plete:
class Task extends React.Component {
constructor () {
super()
this.state {
tasks: null
}
}
ponentDidMount () {
fetch('/task')
.then((data) => {
return data.json()
})
.then((json) => {
this.setState({ tasks: json.tasks })
})
}
renderTaskList () {
if (this.state.tasks) {
return (
<ul>
{this.state.tasks.map((task, i) => <li key={i}>{task.name}</li>)}
</ul>
)
}
return <p>Loading tasks...</p>
}
render () {
return (
<div>
<h1>Tasks</h1>
{this.renderTaskList()}
</div>
)
}
}
Edit: Re-reading this answer, I just wanted to note that it is not necessary to initialize the tasks
property of the state object in this case. You could also just do something like:
this.state = {}
However, I think there is some value in explicitly naming the various properties of your state object, even if they are initialized as null
. This allows you to write ponents whose state is documented in the constructor, and will prevent you or your teammates from later guessing how a ponent's state is modeled.