Implement React Context API

- Move API GET request to /v2/config out to the top level of our App.
- Store /v2/config response data in sessionStorage.
- Use Context API to pass down relevant data to Organizations component.
- Wrap our AnsibleSelect component as a context consumer and pass in the list of Ansible Environments of the logged in user.
- Clear sessionStorage object when user logs out.
- Update unit tests.
This commit is contained in:
kialam
2018-12-17 11:44:11 -05:00
parent 7ea5ea2ecd
commit b8fc402d55
8 changed files with 115 additions and 41 deletions

View File

@@ -1,4 +1,6 @@
import React, { Fragment } from 'react';
import { ConfigContext } from './context';
import {
Redirect,
Switch,
@@ -22,7 +24,7 @@ import {
import { global_breakpoint_md as breakpointMd } from '@patternfly/react-tokens';
import api from './api';
import { API_LOGOUT } from './endpoints';
import { API_LOGOUT, API_CONFIG } from './endpoints';
import HelpDropdown from './components/HelpDropdown';
import LogoutButton from './components/LogoutButton';
@@ -90,15 +92,19 @@ const SideNavItems = ({ items, history }) => {
};
class App extends React.Component {
constructor (props) {
constructor(props) {
super(props);
const isNavOpen = typeof window !== 'undefined' && window.innerWidth >= parseInt(breakpointMd.value, 10);
this.state = {
isNavOpen
isNavOpen,
};
}
getSessionObject(key) {
return JSON.parse(sessionStorage.getItem(key) || '{}');
}
onNavToggle = () => {
this.setState(({ isNavOpen }) => ({ isNavOpen: !isNavOpen }));
};
@@ -110,9 +116,19 @@ class App extends React.Component {
onDevLogout = async () => {
await api.get(API_LOGOUT);
this.setState({ activeGroup: 'views_group', activeItem: 'views_group_dashboard' });
if (sessionStorage.config) {
sessionStorage.clear();
}
}
render () {
async componentDidMount() {
// Grab our config data from the API and store in sessionStorage
if (!sessionStorage.config) {
const { data } = await api.get(API_CONFIG);
sessionStorage.setItem('config', JSON.stringify(data));
}
}
render() {
const { isNavOpen } = this.state;
const { logo, loginInfo, history } = this.props;
@@ -302,7 +318,9 @@ class App extends React.Component {
<ConditionalRedirect shouldRedirect={() => !api.isAuthenticated()} redirectPath="/login" path="/projects" component={Projects} />
<ConditionalRedirect shouldRedirect={() => !api.isAuthenticated()} redirectPath="/login" path="/inventories" component={Inventories} />
<ConditionalRedirect shouldRedirect={() => !api.isAuthenticated()} redirectPath="/login" path="/inventory_scripts" component={InventoryScripts} />
<ConditionalRedirect shouldRedirect={() => !api.isAuthenticated()} redirectPath="/login" path="/organizations" component={Organizations} />
<ConfigContext.Provider value={this.getSessionObject('config')}>
<ConditionalRedirect shouldRedirect={() => !api.isAuthenticated()} redirectPath="/login" path="/organizations" component={Organizations} />
</ConfigContext.Provider>
<ConditionalRedirect shouldRedirect={() => !api.isAuthenticated()} redirectPath="/login" path="/users" component={Users} />
<ConditionalRedirect shouldRedirect={() => !api.isAuthenticated()} redirectPath="/login" path="/teams" component={Teams} />
<ConditionalRedirect shouldRedirect={() => !api.isAuthenticated()} redirectPath="/login" path="/credential_types" component={CredentialTypes} />

View File

@@ -1,4 +1,5 @@
import React from 'react';
import {
FormGroup,
Select,
@@ -16,19 +17,19 @@ class AnsibleSelect extends React.Component {
}
render() {
const { hidden } = this.props;
if (hidden) {
return null;
} else {
if (this.props.data.length > 1) {
return (
<FormGroup label={this.props.labelName} fieldId="ansible-select">
<Select value={this.props.selected} onChange={this.onSelectChange} aria-label="Select Input">
{this.props.data.map((env, index) => (
<SelectOption isDisabled={env.disabled} key={index} value={env} label={env} />
{this.props.data.map((datum, index) => (
<SelectOption isDisabled={datum.disabled} key={index} value={datum} label={datum} />
))}
</Select>
</FormGroup>
);
)
}
else {
return null;
}
}
}

3
src/context.jsx Normal file
View File

@@ -0,0 +1,3 @@
import React from "react";
export const ConfigContext = React.createContext({});

View File

@@ -1,4 +1,5 @@
import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import {
PageSection,
PageSectionVariants,
@@ -15,7 +16,8 @@ import {
CardBody,
} from '@patternfly/react-core';
import { API_ORGANIZATIONS, API_CONFIG } from '../../../endpoints';
import { ConfigContext } from '../../../context';
import { API_ORGANIZATIONS } from '../../../endpoints';
import api from '../../../api';
import AnsibleSelect from '../../../components/AnsibleSelect'
const { light } = PageSectionVariants;
@@ -35,8 +37,6 @@ class OrganizationAdd extends React.Component {
description: '',
instanceGroups: '',
custom_virtualenv: '',
custom_virtualenvs: [],
hideAnsibleSelect: true,
};
onSelectChange(value, _) {
@@ -61,17 +61,10 @@ class OrganizationAdd extends React.Component {
this.resetForm();
}
async componentDidMount() {
const { data } = await api.get(API_CONFIG);
this.setState({ custom_virtualenvs: [...data.custom_virtualenvs] });
if (this.state.custom_virtualenvs.length > 1) {
// Show dropdown if we have more than one ansible environment
this.setState({ hideAnsibleSelect: !this.state.hideAnsibleSelect });
}
}
render() {
const { name } = this.state;
const enabled = name.length > 0; // TODO: add better form validation
return (
<Fragment>
<PageSection variant={light} className="pf-m-condensed">
@@ -113,13 +106,16 @@ class OrganizationAdd extends React.Component {
onChange={this.handleChange}
/>
</FormGroup>
<AnsibleSelect
labelName="Ansible Environment"
selected={this.state.custom_virtualenv}
selectChange={this.onSelectChange}
data={this.state.custom_virtualenvs}
hidden={this.state.hideAnsibleSelect}
/>
<ConfigContext.Consumer>
{({ custom_virtualenvs }) =>
<AnsibleSelect
labelName="Ansible Environment"
selected={this.state.custom_virtualenv}
selectChange={this.onSelectChange}
data={custom_virtualenvs}
/>
}
</ConfigContext.Consumer>
</Gallery>
<ActionGroup className="at-align-right">
<Toolbar>
@@ -140,4 +136,8 @@ class OrganizationAdd extends React.Component {
}
}
OrganizationAdd.contextTypes = {
custom_virtualenvs: PropTypes.array,
};
export default OrganizationAdd;