Home > Software engineering >  Pushing form data onto an array in React
Pushing form data onto an array in React

Time:04-27

I've got some parsed CSV data rendered onto a page in a React App and I want to add a form that pushes input onto the end of it when submitted.

I've managed to get a form that returns an alert with the input as JSON but have so far not been able to push it onto the end of the array.

I'm new to this and just trying to learn it as I go as I need it for a project but having real trouble getting to grips with it.

My entire code looks like this:

import React, { useState, useEffect, push } from "react";
import "./App.css";
import Papa from 'papaparse';
import data from './RentFlagDB.csv'
import { Formik } from 'formik';
import { useFormik } from 'formik';


export default function Archive () {

    const [parsedCsvData, setParsedCsvData] = useState([]);
    useEffect(() => {
        async function getData() {
            const response = await fetch("./RentFlagDB.csv");
            const reader = response.body.getReader();
            const result = await reader.read(); // raw array
            const decoder = new TextDecoder("utf-8");
            const csv = decoder.decode(result.value); // the csv text
            const results = Papa.parse(csv, { header: true, }); // object with { data, errors, meta }
            const rows = results.data; // array of objects
            setParsedCsvData(rows);
        }
        getData();
    }, []);
    return (
        <div className="Archive">
            <table className="ArchiveTable">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Address</th>
                        <th>Postcode</th>
                        <th>Issue</th>
                        <th>Date</th>
                        <th>Score</th>
                    </tr>
                </thead>
                <tbody>
                    {parsedCsvData &&
                        parsedCsvData.map((parsedData, index) => (
                            <tr key={index}>
                                <td>{parsedData.Name}</td>
                                <td>{parsedData.Address}</td>
                                <td>{parsedData.Postcode}</td>
                                <td>{parsedData.Issue}</td>
                                <td>{parsedData.Date}</td>
                                <td>{parsedData.Score}</td>
                            </tr>
                        ))}
                </tbody>
            </table>
        </div>
    );
    const SignupForm = () => {

      const formik = useFormik({
        initialValues: {
          Username: '',
          Address: '',
          Postcode: '',
          Details: '',
          Score: '',
        },
        onSubmit: values => {
          alert(JSON.stringify(values, null, 2));
        },
      });
      return (
        <form onSubmit={formik.handleSubmit}>
          <label htmlFor="Username">Username</label>
          <input
            id="Username"
            name="Username"
            type="text"
            onChange={formik.handleChange}
            value={formik.values.Username}
            onSubmit= {() => {push.getElementByID("Username"); }}
          />

          <label htmlFor="Address">Address</label>
          <input
            id="Address"
            name="Address"
            type="textarea"
            onChange={formik.handleChange}
            value={formik.values.Address}
            onSubmit={() => { push.getElementByID("Address"); }}
          />

          <label htmlFor="Postcode">Postcode</label>
          <input
            id="Postcode"
            name="Postcode"
            type="text"
            onChange={formik.handleChange}
            value={formik.values.Postcode}
            onSubmit= {() => { push.getElementByID("Postcode"); }}
          />
          <label htmlFor="Details">Details</label>
          <input
            id="Details"
            name="Details"
            type="textarea"
            onChange={formik.handleChange}
            value={formik.values.Details}
            onSubmit= {() => { push.getElementByID("Details!"); }}
          />
          <label htmlFor="Score">Score</label>
          <input
            id="Score"
            name="Score"
            type="number"
            onChange={formik.handleChange}
            value={formik.values.Score}
            onSubmit= {() => {push.getElementByID("Score"); }}
          />

          <button type="submit">Submit</button>

        </form>
      );
    };

  }

The bit I believe needs changing looks like this, although it's very likely I'm wrong:

      onSubmit: values => {
          alert(JSON.stringify(values, null, 2));
        },
      });
      return (
        <form onSubmit={formik.handleSubmit}>

CodePudding user response:

To push value to the end of the parsedCsvData, you can try:

const formik = useFormik({
  onSubmit: values => {
    setParsedCsvData([...parsedCsvData, values]);
  },
});

By the way, you don't need to explicitly use onChange and value with formik, because it does all the magic under the hood, using React Context. So you can remove these. Also, I am not sure about all these onSubmit handlers for form inputs, what is the purpose?

If you use useFormik hook, you can wrap your form with FormikProvider like this:

<FormikProvider value={formik}>
  <Form>
    ...
  </Form>
</FormikProvider>
  • Related