Created
April 3, 2019 20:50
-
-
Save cleverbeagle/d825a696dd69d552e9145b8b21b36b2c to your computer and use it in GitHub Desktop.
Example Add Ons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
import Composer from './imports/ui/components/Composer/Composer'; | |
class AddOns extends React.Component { | |
state = { | |
addOns: [], | |
}; | |
componentWillReceiveProps(nextProps) { | |
// NOTE: Assume that addOns is coming from a GraphQL query that's returning addons for the current vehicle. | |
if (nextProps.addOns) { | |
this.setState({ addOns: nextProps.addOns }); | |
} | |
} | |
handleToggleAddOn = (addOn, isEnabled) => { | |
const { vehicleId, updateAddOns } = this.props; | |
const vehicleAddOns = [...this.state.addOns]; | |
const existingVehicleAddOn = vehicleAddOns.find(({ id }) => id === addOn.id); | |
if (existingVehicleAddOn) { | |
existingVehicleAddOn.isEnabled = isEnabled; | |
} else { | |
vehicleAddOns.push({ | |
inerhitedFrom: addOn.id, // NOTE: Assume this is the original ID if we hit this else block. | |
_id: randomIdGenerator(), | |
name: addOn.name, | |
isEnabled, | |
}); | |
} | |
updateVehicleAddOns({ | |
variables: { | |
vehicleId, | |
addOns: vehicleAddOns, | |
}, | |
}); | |
}; | |
render() { | |
const { originalAddOns } = this.props; | |
return ( | |
<React.Fragment> | |
<h4>Add Ons</h4> | |
<ul> | |
{originalAddOns.map((originalAddOn) => { | |
const vehicleAddOn = this.state.addOns.find(({ inheritedFrom }) => inheritedFrom === originalAddOn.id); | |
const addOn = vehicleAddOn || originalAddOn; | |
return ( | |
<li> | |
<p>{addOn.name}</p> | |
<Toggle toggled={addOn.isEnabled} onToggle={(toggled) => this.handleToggleAddOn(addOn, toggled)} /> | |
</li> | |
) | |
})} | |
</ul> | |
</React.Fragment> | |
); | |
} | |
} | |
AddOns.propTypes = { | |
// prop: PropTypes.string.isRequired, | |
}; | |
export default compose( | |
graphql( | |
gql` | |
query vehicleAddOns($vehicleId: ID!) { | |
vehicleAddOns(vehicleId: $vehicleId) { | |
_id | |
name | |
inheritedFrom | |
isEnabled | |
} | |
} | |
`, { | |
name: 'addOns', | |
options: ({ vehicleId }) => { | |
return { | |
variables: { | |
vehicleId, | |
}, | |
} | |
}, | |
}), | |
graphql(gql` | |
originalAddOns { | |
_id | |
name | |
inheritedFrom | |
isEnabled | |
} | |
`, { | |
name: 'addOns', | |
}) | |
)(AddOns); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment