ArpitB

formData

Aug 22nd, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Diff 13.90 KB | None | 0 0
  1. diff --git a/components/fetchCalls.js b/components/fetchCalls.js
  2. index 679defe..929e127 100644
  3. --- a/components/fetchCalls.js
  4. +++ b/components/fetchCalls.js
  5. @@ -2,67 +2,75 @@ const baseUrl = process.env.baseUrl;
  6.  const form_id = process.env.form_id;
  7.  
  8.  const fetchBearerToken = () => {
  9. -  return fetch(baseUrl + "/oauth/token", {
  10. -    method: "POST",
  11. -    body: JSON.stringify({
  12. -      scope: "*",
  13. -      client_secret: process.env.client_secret,
  14. -      client_id: process.env.client_id,
  15. -      grant_type: "client_credentials" //replace it with client_credentials
  16. +    return fetch(baseUrl + '/oauth/token', {
  17. +        method: 'POST',
  18. +        body: JSON.stringify({
  19. +            scope: '*',
  20. +            client_secret: process.env.client_secret,
  21. +            client_id: process.env.client_id,
  22. +            grant_type: 'client_credentials' //replace it with client_credentials
  23. +        })
  24.      })
  25. -  })
  26. -    .then(response => {
  27. -      if (response.ok) {
  28. -        return response.json();
  29. -      } else {
  30. -        throw new Error(
  31. -          "Something went wrong, response code is",
  32. -          response.status
  33. -        );
  34. -      }
  35. -    })
  36. -    .catch(err => console.error(err));
  37. +        .then(response => {
  38. +            if (response.ok) {
  39. +                return response.json();
  40. +            } else {
  41. +                throw new Error(
  42. +                    'Something went wrong, response code is',
  43. +                    response.status
  44. +                );
  45. +            }
  46. +        })
  47. +        .catch(err => console.error(err));
  48.  };
  49.  
  50.  const fetchFormFields = () => {
  51. -  return fetch(
  52. -    baseUrl +
  53. -      "/api/v3/forms/" +
  54. -      form_id +
  55. -      "/attributes?order=asc&orderby=priority"
  56. -  )
  57. -    .then(response => {
  58. -      if (response.ok) {
  59. -        return response.json();
  60. -      } else {
  61. -        throw new Error(
  62. -          "Something went wrong, response code is",
  63. -          response.status
  64. -        );
  65. -      }
  66. -    })
  67. -    .catch(err => console.error(err));
  68. +    return fetch(
  69. +        baseUrl +
  70. +            '/api/v3/forms/' +
  71. +            form_id +
  72. +            '/attributes?order=asc&orderby=priority'
  73. +    )
  74. +        .then(response => {
  75. +            if (response.ok) {
  76. +                return response.json();
  77. +            } else {
  78. +                throw new Error(
  79. +                    'Something went wrong, response code is',
  80. +                    response.status
  81. +                );
  82. +            }
  83. +        })
  84. +        .catch(err => console.error(err));
  85.  };
  86.  
  87.  // Make a post request to Ushahidi sever
  88.  const postFormData = (formData, access_token) => {
  89. -  return fetch(baseUrl + "/api/v3/posts", {
  90. -    method: "POST",
  91. -    body: JSON.stringify(formData),
  92. -    headers: {
  93. -      Accept: "application/json",
  94. -      "Content-Type": "application/json",
  95. -      Authorization: `Bearer ${access_token}`
  96. -    }
  97. -  })
  98. -    .then(response => {
  99. -      return response;
  100. +    let postData = {
  101. +        title: formData.title,
  102. +        content: formData.description,
  103. +        values: formData.values,
  104. +        form: {
  105. +            id: form_id
  106. +        }
  107. +    };
  108. +    return fetch(baseUrl + '/api/v3/posts', {
  109. +        method: 'POST',
  110. +        body: JSON.stringify(postData),
  111. +        headers: {
  112. +            Accept: 'application/json',
  113. +            'Content-Type': 'application/json',
  114. +            Authorization: `Bearer ${access_token}`
  115. +        }
  116.      })
  117. -    .catch(error => console.log(error));
  118. +        .then(response => {
  119. +            return response;
  120. +        })
  121. +        .catch(error => console.log(error));
  122.  };
  123.  
  124.  module.exports = {
  125. -  fetchBearerToken,
  126. -  fetchFormFields,
  127. -  postFormData
  128. +    fetchBearerToken,
  129. +    fetchFormFields,
  130. +    postFormData
  131.  };
  132. diff --git a/components/form.js b/components/form.js
  133. index cf61e09..11e8e80 100644
  134. --- a/components/form.js
  135. +++ b/components/form.js
  136. @@ -1,171 +1,191 @@
  137. -import React from "react";
  138. -import Link from "next/link";
  139. -import { fetchBearerToken, fetchFormFields, postFormData } from "./fetchCalls";
  140. +import React from 'react';
  141. +import Link from 'next/link';
  142. +import { fetchBearerToken, fetchFormFields, postFormData } from './fetchCalls';
  143.  
  144.  const baseUrl = process.env.baseUrl;
  145.  
  146.  export default class Form extends React.Component {
  147. -  constructor() {
  148. -    super();
  149. -    this.state = {
  150. -      token: {
  151. -        accessToken: "",
  152. -        expiresIn: 0,
  153. -        refreshToken: "",
  154. -        tokenType: ""
  155. -      },
  156. -      formFields: [],
  157. -      formData: {}
  158. -    };
  159. -  }
  160. -
  161. -  // Make state targets equal to the value of input fields
  162. -  change = e => {
  163. -    this.setState({
  164. -      formData: {
  165. -        ...this.state.formData,
  166. -        [e.target.name]: e.target.value
  167. -      }
  168. -    });
  169. -  };
  170. -
  171. -  isTokenValid() {
  172. -    let isValid = false;
  173. -
  174. -    const currentTime = new Date().getTime();
  175. -    const tokenFetchTime = this.state.token.fetching_time;
  176. -    const expirationTime = this.state.token.expires_in;
  177. -
  178. -    if (currentTime < tokenFetchTime + expirationTime) {
  179. -      isValid = true;
  180. +    constructor() {
  181. +        super();
  182. +        this.state = {
  183. +            tempData: {},
  184. +            token: {
  185. +                accessToken: '',
  186. +                expiresIn: 0,
  187. +                refreshToken: '',
  188. +                tokenType: ''
  189. +            },
  190. +            formFields: [],
  191. +            formData: {}
  192. +        };
  193.      }
  194.  
  195. -    return isValid;
  196. -  }
  197. +    isTokenValid() {
  198. +        let isValid = false;
  199.  
  200. -  getToken() {
  201. -    let token = JSON.parse(localStorage.getItem("Bearer Token"));
  202. -    if (!token || this.isTokenValid()) {
  203. -      fetchBearerToken().then(data =>
  204. -        this.setState({
  205. -          token: { ...data, fetching_time: new Date().getTime() }
  206. -        })
  207. -      );
  208. -    } else {
  209. -      this.setState({ token: token });
  210. +        const currentTime = new Date().getTime();
  211. +        const tokenFetchTime = this.state.token.fetching_time;
  212. +        const expirationTime = this.state.token.expires_in;
  213. +
  214. +        if (currentTime < tokenFetchTime + expirationTime) {
  215. +            isValid = true;
  216. +        }
  217. +
  218. +        return isValid;
  219.      }
  220. -  }
  221.  
  222. -  getFormFields() {
  223. -    // Fetch the data form fields from API, use it in state
  224. -    let formFields = JSON.parse(localStorage.getItem("Form Fields"));
  225. -    if (!(Array.isArray(formFields) && formFields.length)) {
  226. -      fetchFormFields().then(data =>
  227. -        this.setState({
  228. -          formFields: data.results
  229. -        })
  230. -      );
  231. -    } else {
  232. -      this.setState({
  233. -        formFields: formFields
  234. -      });
  235. +    getToken() {
  236. +        let token = JSON.parse(localStorage.getItem('Bearer Token'));
  237. +        if (!token || this.isTokenValid()) {
  238. +            fetchBearerToken().then(data =>
  239. +                this.setState({
  240. +                    token: { ...data, fetching_time: new Date().getTime() }
  241. +                })
  242. +            );
  243. +        } else {
  244. +            this.setState({ token: token });
  245. +        }
  246. +    }
  247. +
  248. +    getFormFields() {
  249. +        // Fetch the data form fields from API, use it in state
  250. +        let formFields = JSON.parse(localStorage.getItem('Form Fields'));
  251. +        if (!(Array.isArray(formFields) && formFields.length)) {
  252. +            fetchFormFields().then(data =>
  253. +                this.setState({
  254. +                    formFields: data.results
  255. +                })
  256. +            );
  257. +        } else {
  258. +            this.setState({
  259. +                formFields: formFields
  260. +            });
  261. +        }
  262. +    }
  263. +
  264. +    isOnlineEvent = e => {
  265. +        let formDataArray = JSON.parse(
  266. +            localStorage.getItem('Failed Form Submission Data')
  267. +        );
  268. +
  269. +        failedPosts = [];
  270. +
  271. +        if (!formDataArray) {
  272. +            return;
  273. +        } else {
  274. +            formDataArray.map(formData => {
  275. +                postFormData(formData, this.state.token.access_token).then(
  276. +                    response => {
  277. +                        if (!response.ok) {
  278. +                            failedPosts.push(formData);
  279. +                        }
  280. +                    }
  281. +                );
  282. +            });
  283. +
  284. +            if (failedPosts.length === 0) {
  285. +                localStorage.setItem(
  286. +                    'Failed Form Submission Data',
  287. +                    JSON.stringify(failedPosts)
  288. +                );
  289. +            } else {
  290. +                localStorage.removeItem('Failed Form Submission Data');
  291. +            }
  292. +        }
  293. +    };
  294. +
  295. +    componentDidMount() {
  296. +        this.getFormFields();
  297. +        this.getToken();
  298.      }
  299. -  }
  300. -
  301. -  isOnlineEvent = e => {
  302. -    let formDataArray = JSON.parse(
  303. -      localStorage.getItem("Failed Form Submission Data")
  304. -    );
  305. -
  306. -    failedPosts = [];
  307. -
  308. -    if (!formDataArray) {
  309. -      return;
  310. -    } else {
  311. -      formDataArray.map(formData => {
  312. -        postFormData(formData, this.state.token.access_token).then(response => {
  313. -          if (!response.ok) {
  314. -            failedPosts.push(formData);
  315. -          }
  316. -        });
  317. -      });
  318.  
  319. -      if (failedPosts.length === 0) {
  320. +    componentDidUpdate(prevProps, prevState) {
  321.          localStorage.setItem(
  322. -          "Failed Form Submission Data",
  323. -          JSON.stringify(failedPosts)
  324. +            'Form Fields',
  325. +            JSON.stringify(this.state.formFields)
  326.          );
  327. -      } else {
  328. -        localStorage.removeItem("Failed Form Submission Data");
  329. -      }
  330. +        localStorage.setItem('Bearer Token', JSON.stringify(this.state.token));
  331. +        window.addEventListener('online', this.isOnlineEvent);
  332.      }
  333. -  };
  334. -
  335. -  componentDidMount() {
  336. -    this.getFormFields();
  337. -    this.getToken();
  338. -  }
  339. -
  340. -  componentDidUpdate(prevProps, prevState) {
  341. -    localStorage.setItem("Form Fields", JSON.stringify(this.state.formFields));
  342. -    localStorage.setItem("Bearer Token", JSON.stringify(this.state.token));
  343. -    window.addEventListener("online", this.isOnlineEvent);
  344. -  }
  345. -
  346. -  // Handler html For when the submit button is pressed
  347. -  onSubmit = e => {
  348. -    e.preventDefault();
  349. -   let formDataArray= []
  350. -    if (navigator.onLine) {
  351. -      postFormData(this.state.formData, this.state.token.access_token);
  352. -    } else {
  353. -      let formDataArray = JSON.parse(
  354. -        localStorage.getItem("Failed Form Submission Data")
  355. -      );
  356. -      formDataArray.push(this.state.formData)
  357. -      
  358. -      localStorage.setItem(
  359. -        "Failed Form Submission Data",
  360. -        JSON.stringify(formDataArray)
  361. -      );
  362. +
  363. +    // Handler html For when the submit button is pressed
  364. +    onSubmit = e => {
  365. +        e.preventDefault();
  366. +        let formDataArray = [];
  367. +        if (navigator.onLine) {
  368. +            postFormData(this.state.formData, this.state.token.access_token);
  369. +        } else {
  370. +            let formDataArray = JSON.parse(
  371. +                localStorage.getItem('Failed Form Submission Data')
  372. +            );
  373. +            formDataArray.push(this.state.formData);
  374. +
  375. +            localStorage.setItem(
  376. +                'Failed Form Submission Data',
  377. +                JSON.stringify(formDataArray)
  378. +            );
  379. +        }
  380. +        this.setState({
  381. +            formData: {}
  382. +        });
  383. +    };
  384. +
  385. +    // Make state targets equal to the value of input fields
  386. +    change = e => {
  387. +        data = this.state.tempData;
  388. +        if (e.target.name === 'title' || e.target.name === 'description') {
  389. +            data = { ...data, [e.target.name]: e.target.value };
  390. +        } else {
  391. +            data = {
  392. +                ...data,
  393. +                values: {
  394. +                    ...data.values,
  395. +                    [e.target.key]: e.target.values
  396. +                }
  397. +            };
  398. +        }
  399. +        this.state.tempData = data;
  400. +
  401. +        this.setState({
  402. +            formData: {
  403. +                ...this.state.formData,
  404. +                data
  405. +            }
  406. +        });
  407. +    };
  408. +
  409. +    // Create an array of elements to be rendered in the form
  410. +    FormInputs = props => {
  411. +        return props.fields.map(field => {
  412. +            return (
  413. +                <div key={field.key}>
  414. +                    <label className="background" htmlFor={field.label}>
  415. +                        {field.label}
  416. +                    </label>
  417. +                    <input
  418. +                        className="input"
  419. +                        type={field.input}
  420. +                        name={field.type}
  421. +                        key={field.key}
  422. +                        placeholder={`Enter the ${field.type}`}
  423. +                        value={this.state.formData[field.type]}
  424. +                        onChange={e => this.change(e)}
  425. +                    />
  426. +                </div>
  427. +            );
  428. +        });
  429. +    };
  430. +
  431. +    render() {
  432. +        return (
  433. +            <form>
  434. +                <this.FormInputs fields={this.state.formFields} />
  435. +                <div>
  436. +                    <button className="button" onClick={e => this.onSubmit(e)}>
  437. +                        Submit
  438. +                    </button>
  439. +                </div>
  440. +            </form>
  441. +        );
  442.      }
  443. -    this.setState({
  444. -      formData: {}
  445. -    });
  446. -  };
  447. -
  448. -  // Create an array of elements to be rendered in the form
  449. -  FormInputs = props => {
  450. -    return props.fields.map(field => {
  451. -      return (
  452. -        <div key={field.key}>
  453. -          <label className="background" htmlFor={field.label}>
  454. -            {" "}
  455. -            {field.label}{" "}
  456. -          </label>
  457. -          <input
  458. -            className="input"
  459. -            type={field.input}
  460. -            name={field.label}
  461. -            placeholder={`Enter the ${field.label}`}
  462. -            value={this.state.formData[field.label]}
  463. -            onChange={e => this.change(e)}
  464. -          />
  465. -        </div>
  466. -      );
  467. -    });
  468. -  };
  469. -
  470. -  render() {
  471. -    return (
  472. -      <form>
  473. -        <this.FormInputs fields={this.state.formFields} />
  474. -        <div>
  475. -          <button className="button" onClick={e => this.onSubmit(e)}>
  476. -            Submit
  477. -          </button>
  478. -        </div>
  479. -      </form>
  480. -    );
  481. -  }
  482.  }
Add Comment
Please, Sign In to add comment