Reputation: 301
I am developing a simple website which displays data from an API(JSON) into a page using react.
I'm using the fetch() API.
I am able to get the data from the API and set it into the 'App' component state but I'm not able to pass is down to Table and Row components that I've manually created.
class App extends React.Component {
constructor (props) {
super(props)
this.state = {ticker: {}, volume: {}}
this.loadData = this.loadData.bind(this)
this.loadData()
}
loadData () {
fetch(ticker)
.then((resp) => resp.json())
.then((data) => {
this.setState({
ticker: data
})
})
.catch((err) => {
console.log(err)
})
fetch(volume)
.then((resp) => resp.json())
.then((data) => {
this.setState({
volume: data
})
})
.catch((err) => {
console.log(err)
})
}
render () {
return (
<div>
<Navbar />
<div className='container'>
<div className='align'>
<div className='element' />
</div>
<Table volume={this.state.volume} ticker={this.state.ticker} />
</div>
</div>
)
}
}
BOTTOM LINE: I have an API with data, and I have 3 components, Table, which also has a row component. I want to display variables in the Row component which looks like this
<Row img='eth' name='Ethereum' price='' volume='' change='' marketCap='' />
Upvotes: 4
Views: 10180
Reputation: 12054
You constructor :
constructor (props) {
super(props);
this.state = {ticker: {}, volume: {}}
this.loadData = this.loadData.bind(this);
}
For fetching data you need always to use lifecycle component, as componentDidMount
or componentWillMount
, thus :
componentDidMount(){
this.loadData()
}
And then in your state you will have the data.
In your render
method pass it as props to the Table
component:
render(){
return(
<Table volume={this.state.volume} ticker={this.state.ticker} />
)
}
Then in from the Table
component pass it to Row
component as props, thus :
render(){
return(
<Row img='eth' name='Ethereum' price='' volume={this.props.volume} change='' marketCap='' />
)
}
If you have array of objects, something like :
this.state = {
volume: [ {name: "One", size: 1 }, {name: "Two", size: 2 }, ..... ]
}
You'll need to loop through the array and show the Row
component for each object.
Thus, your Table
component should be something as follows:
render(){
return (
<div>{this.props.volume.map(vol => <Row img='eth' name='Ethereum' price='' volume={vol} change='' marketCap='' />) }</div>
)
}
Upvotes: 3
Reputation: 2999
If you make the ajax call in componentDidMount
, then React will rerender when the state changes (https://facebook.github.io/react/docs/react-component.html#componentdidmount). But you still have to anticipate that the volume
and ticker
props will be empty until the request resolves and React rerenders.
Upvotes: 0