Skip to content

Instantly share code, notes, and snippets.

@clintonyeb
Created May 17, 2020 19:57
Show Gist options
  • Save clintonyeb/8756f46e5d8529358940744f43d7bdb6 to your computer and use it in GitHub Desktop.
Save clintonyeb/8756f46e5d8529358940744f43d7bdb6 to your computer and use it in GitHub Desktop.
import React, { Component } from "react";
import { fetchCurrency, changeCurrency } from "../Actions/fetchCurrency";
import { connect } from "react-redux";
import GetCurrencyData from "../Components/getCurrData.js";
import "../App.css";
//We are creating a component class CurrencyCardDisplay by extending a react component
// Read more about react components at https://reactjs.org/docs/react-component.html
class CurrencyCardDisplay extends Component {
//When an instance of a Component is Mounted the following methods are called in order
/*
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
Of the above 4 methods, only 'render' is compulsory to implement'. we are implementing 2 of them in the example below.
*/
constructor(props) {
super(props);
//fetch list of currencies from api using fetchCurrency local method
props.fetchCurrency();
this.state = {
//initial selected currency is null
selectedOption: null,
};
}
//Event triggered on any data change in the form
handleChange = (selectedOption) => {
//selecting the correct currency option
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
};
//Each react component class HAS to define a method render
render() {
// populate list of countries possible
const availableCountries = this.props.availableCountries.filter((x) => {
return this.props.activeSubscription.indexOf(x) === -1;
});
// select currently active subscription
const activeSubscription = this.props.activeSubscription || [];
return (
<div className="main-app">
{activeSubscription.map((key, index) => {
return (
<div key={key}>
<GetCurrencyData
onSubscriptionChange={(code, index) => {
this.props.changeCurrency(code, index);
}}
keyId={index}
country={key}
availableCountries={availableCountries}
/>
</div>
);
})}
</div>
);
}
}
const mapStateToProps = (state) => state.currency;
const mapDispatchToProps = (dispatch) => ({
//calls fetchCurrency Api from fetchCurrency.js
fetchCurrency: () => dispatch(fetchCurrency()),
//calls changeCurrency Api from fetchCurrency.js
changeCurrency: (code, index) => dispatch(changeCurrency(code, index)),
});
//class exposes a connect method
export default connect(
mapStateToProps,
mapDispatchToProps
)(CurrencyCardDisplay);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment