index.tsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import React from 'react';
  2. import Navbar from 'components/Navbar';
  3. import Input from 'components/Input';
  4. import Button from 'components/Button';
  5. import RecipeForm from 'components/RecipeForm';
  6. import Spinner from 'components/Spinner';
  7. import { toast } from "react-toastify";
  8. import './styles.scss';
  9. import Recipe, { _recipe } from 'types/recipes';
  10. import { scrapeRecipe, saveRecipe } from '../services';
  11. interface CreateRecipeProps {
  12. };
  13. interface CreateRecipeState {
  14. scrapeUrl: string,
  15. form: Recipe,
  16. scrapingRecipe: boolean,
  17. };
  18. class CreateRecipe extends React.Component<any, CreateRecipeState> {
  19. constructor(props: CreateRecipeProps) {
  20. super(props);
  21. this.state = {
  22. form: {
  23. ..._recipe,
  24. },
  25. scrapeUrl: '',
  26. scrapingRecipe: false,
  27. }
  28. }
  29. scrapeRecipe = () => {
  30. if (this.state.scrapeUrl) {
  31. this.setState({
  32. scrapingRecipe: true
  33. }, () => {
  34. scrapeRecipe(this.state.scrapeUrl).then(recipe => {
  35. this.setState({
  36. scrapingRecipe: false,
  37. form: {
  38. ...recipe,
  39. details: {
  40. ...recipe.details,
  41. url: this.state.scrapeUrl,
  42. },
  43. tags: recipe.tags || [],
  44. course: recipe.course || [],
  45. }
  46. })
  47. }).catch(e => {
  48. toast.error("There was an error scraping the recipe: " + e);
  49. this.setState({
  50. scrapingRecipe: false
  51. })
  52. })
  53. })
  54. }
  55. }
  56. saveRecipe = (recipe: Recipe) => {
  57. saveRecipe(recipe)
  58. .then(response => {
  59. if (response.status === 200) {
  60. toast.success("Recipe created correctly!");
  61. this.goToViewList();
  62. } else {
  63. toast.error("There was an error saving the recipe: " + response.statusText);
  64. }
  65. })
  66. }
  67. goToViewList = () => {
  68. this.props.history.push('/recipes');
  69. }
  70. render() {
  71. const { scrapeUrl, form, scrapingRecipe } = this.state;
  72. return (
  73. <div>
  74. {
  75. scrapingRecipe && (<Spinner/>)
  76. }
  77. <Navbar
  78. title="Create a recipe"
  79. >
  80. <Input
  81. label='scrape recipe'
  82. value={scrapeUrl}
  83. onChange={(e: any)=> this.setState({scrapeUrl: e.currentTarget.value})}
  84. />
  85. <Button onClick={this.scrapeRecipe} outlined>Scrape</Button>
  86. </Navbar>
  87. <div className="cbk-create-recipe">
  88. <RecipeForm
  89. initialValues={form}
  90. onSubmit={(recipe) => this.saveRecipe(recipe)}
  91. onCancel={this.goToViewList}
  92. />
  93. </div>
  94. </div>
  95. )
  96. }
  97. }
  98. export default CreateRecipe;