showing results for - "strapi io react"
Elisa
26 Feb 2019
1import React from 'react';
2
3// Parses the JSON returned by a network request
4const parseJSON = resp => (resp.json ? resp.json() : resp);
5
6// Checks if a network request came back fine, and throws an error if not
7const checkStatus = resp => {
8  if (resp.status >= 200 && resp.status < 300) {
9    return resp;
10  }
11  return parseJSON(resp).then(resp => {
12    throw resp;
13  });
14};
15const headers = {
16  'Content-Type': 'application/json',
17};
18
19class App extends React.Component {
20  constructor(props) {
21    super(props);
22    this.state = {
23      modifiedData: {
24        name: '',
25        description: '',
26        categories: [],
27      },
28      allCategories: [],
29      error: null,
30    };
31  }
32
33  componentDidMount = async () => {
34    try {
35      const allCategories = await fetch('http://localhost:1337/categories', {
36        method: 'GET',
37        headers: headers,
38      })
39        .then(checkStatus)
40        .then(parseJSON);
41      this.setState({ allCategories });
42    } catch (error) {
43      this.setState({ error });
44    }
45  };
46
47  handleInputChange = ({ target: { name, value } }) => {
48    this.setState(prev => ({
49      ...prev,
50      modifiedData: {
51        ...prev.modifiedData,
52        [name]: value,
53      },
54    }));
55  };
56
57  handleSubmit = async e => {
58    e.preventDefault();
59
60    try {
61      await fetch('http://localhost:1337/restaurants', {
62        method: 'POST',
63        headers: headers,
64        body: JSON.stringify(this.state.modifiedData),
65      })
66        .then(checkStatus)
67        .then(parseJSON);
68    } catch (error) {
69      this.setState({ error });
70    }
71  };
72
73  renderCheckbox = category => {
74    const {
75      modifiedData: { categories },
76    } = this.state;
77    const isChecked = categories.includes(category.id);
78    const handleChange = () => {
79      if (!categories.includes(category.id)) {
80        this.handleInputChange({
81          target: { name: 'categories', value: categories.concat(category.id) },
82        });
83      } else {
84        this.handleInputChange({
85          target: {
86            name: 'categories',
87            value: categories.filter(v => v !== category.id),
88          },
89        });
90      }
91    };
92
93    return (
94      <div key={category.id}>
95        <label htmlFor={category.id}>{category.name}</label>
96        <input
97          type="checkbox"
98          checked={isChecked}
99          onChange={handleChange}
100          name="categories"
101          id={category.id}
102        />
103      </div>
104    );
105  };
106
107  render() {
108    const { error, allCategories, modifiedData } = this.state;
109
110    // Print error if any
111    if (error) {
112      return <div>An error occured: {error.message}</div>;
113    }
114
115    return (
116      <div className="App">
117        <form onSubmit={this.handleSubmit}>
118          <h3>Restaurants</h3>
119          <br />
120          <label>
121            Name:
122            <input
123              type="text"
124              name="name"
125              onChange={this.handleInputChange}
126              value={modifiedData.name}
127            />
128          </label>
129          <label>
130            Description:
131            <input
132              type="text"
133              name="description"
134              onChange={this.handleInputChange}
135              value={modifiedData.description}
136            />
137          </label>
138          <div>
139            <br />
140            <b>Select categories</b>
141            {allCategories.map(this.renderCheckbox)}
142          </div>
143          <br />
144          <button type="submit">Submit</button>
145        </form>
146      </div>
147    );
148  }
149}
150
151export default App;
152