Reputation: 821
Im going to create an app to shows top 5 cryptocurrencies price. I create a list of coins and pass it to FlatList and every card is specific coin details. But in my implementation all cards shows same price and that is expected because I have just single price in state. Appreciate for any idea help in this matter.
coinReducer.js
const INITIAL_STATE = {
price: '',
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case COIN_PRICE:
return { ...state, price: action.payload };
default:
return state;
}
};
coinAction.js
const URL = 'https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC,ETH,XRP,BCH,EOS&tsyms=USD';
export const getCoinPrice = (symbol) => async (dispatch) => {
try {
const response = await axios.get(URL);
return dispatch({
type: COIN_PRICE,
payload: response.data.RAW[symbol].USD.PRICE,
});
} catch (error) {
throw error;
}
};
cardSection.js
class Card extends Component {
componentWillMount() {
this.props.getCoinPrice(this.props.item.symbol);
}
render() {
return (
<View>
<Text>
this.props.price
</Text>
</View>
)
}
}
export default connect(state => ({
price: state.coinPrice.price
}), { getCoinPrice })(Card);
Upvotes: 0
Views: 834
Reputation: 1596
I think you can keep all the currency's price in the store instead of fetching and update only one of them every time.
Change your reducer into:
const INITIAL_STATE = {
price: {},
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case COIN_PRICE:
return { ...state, price: { ...state.price, action.payload } };
default:
return state;
}
};
And then change the action into
const URL = 'https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC,ETH,XRP,BCH,EOS&tsyms=USD';
export const getCoinPrice = (symbol) => async (dispatch) => {
try {
const response = await axios.get(URL);
const payload = {};
payload[symbol] = response.data.RAW[symbol].USD.PRICE;
return dispatch({
type: COIN_PRICE,
payload,
});
} catch (error) {
throw error;
}
};
And finally your component into:
class Card extends Component {
componentWillMount() {
this.props.getCoinPrice(this.props.item.symbol);
}
render() {
return (
<View>
<Text>
{this.props.price[this.props.item.symbol]}
</Text>
</View>
)
}
}
export default connect(state => ({
price: state.coinPrice.price
}), { getCoinPrice })(Card);
Upvotes: 2