0

I am currently learning React and creating a Mock website so that I can learn as you build.

The website is very simple and it gives user information about animal they can find in zoo.

In one of the page users can add new information about animals.

Below you will the code of that page.

Input.js

> import React, { useState } from "react";
import { Row, Col, Form, FormGroup, Label, Input, Button } from "reactstrap";
import data from "../Components/data.json"


export const InputForm = props => {

    const {updateDetailsArray} = props;
    
    const initialInputState = { Species: "", Facts: "" };
   

    const [eachEntry, setEachEntry] = useState(initialInputState);

    const {Species, Facts} = eachEntry;

      
    const handleInputChange = e => {
        setEachEntry({...eachEntry,[e.target.name]: e.target.value});
    };

    const handleFinalSubmit = e => {
        updateDetailsArray(eachEntry)
    };

  return (
  <div>
    <Row>
      <Col sm="12" md={{ size: 6, offset: 3 }} className="text-center">
        <h2>Add Animal</h2>
      </Col>
    </Row>
    <Row className="mt-4">
      <Col sm="12" md={{ size: 6, offset: 3 }}>
        <Form>
          <FormGroup>
            <Label for="Species">Species</Label>
            <Input name="Species" 
            placeholder="What kind of animal is it?"
            onChange={handleInputChange}
            value={Species}
            ></Input>
          </FormGroup>
          <FormGroup>
            <Label for="Facts">Facts</Label>
            <Input name="Facts" 
            placeholder="Enter animal details"
            onChange={handleInputChange}
            value={Facts}
            ></Input>
          </FormGroup>
          <Button onClick={handleFinalSubmit}>Submit</Button>
        </Form>
      </Col>
    </Row>
  </div> 
  );
};

Output.js

import React from "react";
import { Row, Col, Table } from "reactstrap";


export const Outputsubmitted = props => {
const {details} = props;

  return (
    <div className="mt-4">
    <Row>
      <Col sm="12" md={{ size: 16, offset: 300 }}>
        <Table hover>
          <thead>
            <tr>
              {/* <tr> is row */}
              <th>#</th>
              <th>Species</th>
              <th>Facts</th>
              {/* <th> create the header in the row. <Td> normal data in rows */}
            </tr>
          </thead>
          <tbody>
            <RenderTableData details={details} />
          </tbody>
        </Table>
      </Col>
    </Row>
  </div>
);
};
const RenderTableData = props => {
  const { details } = props;
  var count = 0;
  // starting number 0 for #.
  const finalArray = details.sort((a, b) => b.score - a.score);
  // .sort will organize data alphabetically or ascending order. 
  return Object.keys(finalArray).map((i, o) => {
    // Object.keys = displays keys of the object. E.g Name:Kiro(keys=Name)
    // .map will add a  function to the element and display its results. 
    const { Species, Facts } = finalArray[i];
    count = count + 1;
    return (
      <tr key={count.toString(10)}>
        <th scope="row">{count.toString(10)}</th>
        <td>{Species}</td>
        <td>{Facts}</td>
      </tr>
    );
  });
};

And lastly to display the both of the file. Addnew.js

import {useState} from 'react';
import {InputForm} from './Input';
import {Outputsubmitted} from './Output'


function App() {
    // This usestate will pass on data from parent component(app.js) to child components.
    const [details, setdetails] = useState([]);
    
    const updateDetailsArray = eachEntry => {
      setdetails([...details, eachEntry]);
    };
    return (
      <div className="container mt-4">
          <InputForm updateDetailsArray={updateDetailsArray} />
          <Outputsubmitted details={details} />
        </div>
      );
    }
    export default App;
    
    // updateDetailsArray is a props used in Sumbit button(to pull the newly added data written in eachEntry) and Inputform (to pass the data to 
    // the inputForm(childcomponent)). 
    

When you NPM start it this is what comes up for the add new page. The input data are being saved on the right hand side circled area but when I refresh - it goes away.

After some research, found out that you need to use JSON to save it permanently. Can you show me how to do this please?

Saroj
  • 11
  • 1
  • 4

1 Answers1

1

When you reload the website the information you've saved goes because they aren't saved in permanent memory or file but rather they are saved in the browser cache memory that gets erased every time you refresh the browser.

To do what you are seeking to achieve you have plenty of options:

1. You can save the data to the browser local storage

Local storage is a place in the browser where you can save data.

Saving data to local storage looks like this:

localStorage.setItem('details', 'Some details');

Getting data from local storage looks like this:

localStorage.getItem('details');

Local storage only hold string values so if you want to save an array or object to it you have to stringify it first (stringifying is just turning your array to string) like this:

const arr = [1, 2, 3]
localStorage.setItem("arr", JSON.stringify(arr));

The above code will save the array arr to the browsers' local storage as a string value like follows: "[1,2,3]"

if you want to get the value of the array back you can simply parse the string value (parsing is just converting the localstorage string value to whatever it was before stringifying like an array or object)

arr = JSON.parse(localStorage.getItem("arr"));

You can implement the above in your code as follows: In the file Addnew.js

import {useState} from 'react';
import {InputForm} from './Input';
import {Outputsubmitted} from './Output'


function App() {
    if (localStorage.getItem("details") == null) {
       localStorage.setItem("details", JSON.stringify([]))
    }
    const [details, setdetails] = useState(JSON.parse(localStorage.getItem("details")));
    
    const updateDetailsArray = eachEntry => {
      setdetails([...details, eachEntry]);
      localStorage.setItem("details", JSON.stringify([...details, eachEntry]))
    };
    return (
      <div className="container mt-4">
          <InputForm updateDetailsArray={updateDetailsArray} />
          <Outputsubmitted details={details} />
        </div>
      );
    }
    export default App;

The big downside of local storage is that if the user opened the site from another browser or even cleaned the cache all the data will be erased, so be careful with it and don't ever store critical data in it as you can always see what is in the local storage by opening the application tap in chrome dev tools and selecting Local Storage.

2. You can save the data to a database You can save your data to a database of your choice like MongoDB or MySQL for example and free your mind from all the hassle

2. You can save the data to a local JSON file For this feature, you will need to have a backend to treat the JSON file with a module like the filesystem (fs) module and you can learn more about it from here: https://stackoverflow.com/a/36869835/15075805