content.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import { Query, Mutation } from 'react-apollo'
  2. import { adopt } from 'react-adopt'
  3. import { Formik, Form } from 'formik'
  4. import { TextInput } from '../lib/forms'
  5. import { BLOCKS, CREATE_BLOCK } from '../lib/graphql'
  6. import Overlay from './overlay'
  7. const ContentInput = props => {
  8. const [displayForm, setDisplayForm] = React.useState(false)
  9. const toggleForm = ev => {
  10. ev.preventDefault()
  11. setDisplayForm(!displayForm)
  12. }
  13. return (
  14. <Query query={BLOCKS}>
  15. {({ data, error, loading }) => (
  16. <>
  17. <label>Training type</label>
  18. <div>
  19. <select disabled={(loading || error)}>
  20. {data ? data.trainingTypes.map(trainingType =>
  21. <option key={trainingType.id} value={trainingType.id}>{trainingType.name}</option>
  22. ) : null}
  23. </select>
  24. <button
  25. type='button'
  26. onClick={toggleForm}
  27. >Add
  28. </button>
  29. </div>
  30. {displayForm ? (
  31. <Overlay close={toggleForm}>
  32. <ContentForm />
  33. </Overlay>
  34. ) : null}
  35. <style jsx>
  36. {`
  37. div {
  38. width: 100%;
  39. }
  40. `}
  41. </style>
  42. </>
  43. )}
  44. </Query>
  45. )
  46. }
  47. const ContentAdoption = adopt({
  48. mutation: ({ render }) => (
  49. <Mutation
  50. mutation={CREATE_BLOCK}
  51. refetchQueries={[{ query: BLOCKS }]}
  52. >
  53. {(createTrainingType, { data, error, loading }) => render({ createTrainingType, data, error, loading })}
  54. </Mutation>
  55. ),
  56. form: ({ mutation: { createTrainingType }, render }) => (
  57. <Formik
  58. initialValues={{
  59. name: '',
  60. description: ''
  61. }}
  62. onSubmit={values => createTrainingType({ variables: values })}
  63. >
  64. {render}
  65. </Formik>
  66. )
  67. })
  68. const ContentForm = props => (
  69. <ContentAdoption>{({ mutation, form }) => (
  70. <Form>
  71. <TextInput
  72. label='Name'
  73. name='name'
  74. type='text'
  75. />
  76. <TextInput
  77. label='Description'
  78. name='description'
  79. type='text'
  80. />
  81. <button type='reset'>Reset</button>
  82. <button type='submit'>Save</button>
  83. </Form>
  84. )}
  85. </ContentAdoption>
  86. )
  87. export { ContentForm }
  88. export default ContentInput