Reputation: 60
<div className = 'card'>
<p>{props.rate.code} {props.rate.currency}</p>
<p>{props.rate.mid}
{console.log(props.code)}</p>
</div>
)
In console.log i can see all codes, but on site displays only random few, which changes if i refresh. I really don't have any idea, this is code from tutorial, but I work on another dataset. I have 2 dimensional table with data way i get data
componentDidMount() {
fetch('http://api.nbp.pl/api/exchangerates/tables/A/?format=json')
.then((response) => response.json())
.then(values =>this.setState({currency: values}))
fetch('http://api.nbp.pl/api/exchangerates/tables/B/?format=json')
.then((response) => response.json())
.then(values =>this.setState({currency: values}))
fetch('http://api.nbp.pl/api/exchangerates/tables/C/?format=json')
.then((response) => response.json())
.then(values =>this.setState({currency: values}))
}
using map
{props.currency.map(
(table,index) =>
table.rates.map(rate =>(
<Card key={index+rate.code} rate={rate}/>
)
)
)}
in app component
<CardList currency={this.state.currency}/>
in console i see maybe 200 values, but on site i see randomly 10-100 values
Upvotes: 1
Views: 68
Reputation: 10382
each fetch overwrites the previous currency
state, this way you loose previous data. To avoid you would need to copy the current state while adding the new one:
componentDidMount() {
fetch('http://api.nbp.pl/api/exchangerates/tables/A/?format=json')
.then((response) => response.json())
.then(values =>this.setState(({ currency }) => {currency: [...currency, ...values]}))
fetch('http://api.nbp.pl/api/exchangerates/tables/B/?format=json')
.then((response) => response.json())
.then(values =>this.setState(({ currency }) => {currency: [...currency, ...values]}))
fetch('http://api.nbp.pl/api/exchangerates/tables/C/?format=json')
.then((response) => response.json())
.then(values =>this.setState(({ currency }) => {currency: [...currency, ...values]}))
}
though this looks a little dirty, since you are doing several state updates. You could await each response, then update your state:
async componentDidMount() {
try {
const currencyA = await this.getCurrencyFromTable('A');
const currencyB = await this.getCurrencyFromTable('B');
const currencyC = await this.getCurrencyFromTable('C');
const currency = [...currencyA, ...currencyB, ...currencyC];
this.setState({ currency })
} catch (error) {
console.log(error)
}
}
getCurrencyFromTable(table) {
return fetch(`http://api.nbp.pl/api/exchangerates/tables/${table}/?format=json`)
.then((response) => response.json())
}
Upvotes: 1