sandbox-react/crud/src/components/edit.js

83 lines
1.9 KiB
JavaScript

import React, { useEffect, useState } from 'react'
import array from './array';
import { Link} from 'react-router-dom';
import {useNavigate} from 'react-router-dom';
export default function Edit() {
// Here usestate has been used in order
// to set and get values from the jsx
const [name, setname] = useState('');
const [age, setage] = useState('');
const[id,setid] = useState('');
// used for navigation with logic in javascript
let history = useNavigate()
// getting an index of an entry with an id
var index = array.map(function(e) { return e.id; }).indexOf(id);
// function for handling the edit and
// pushing changes of editing/updating
const handelSubmit = (e) =>{
e.preventDefault(); // preventing from reload
let a = array[index] // getting an index of an array
// putting the value from the input textfield and
// replacing it from existing for updation
a.Name = name
a.Age = age
// redirecting to main page
history('/')
}
// Useeffect take care that page will be rendered only once
useEffect(() => {
setname(localStorage.getItem('Name'))
setage(localStorage.getItem('Age'))
setid(localStorage.getItem('id'))
}, [])
return(
<div>
<h1>Update</h1>
<form
onSubmit={e => handelSubmit(e)}
>
<label>
Enter name (input:{name}):
<input
onChange={e => setname(e.target.value)}
type="text"
placeholder="Enter Name"
/>
</label>
<label>
Enter name (input:{age}):
<input
value={age}
onChange={e => setage(e.target.value)}
type="text"
placeholder="Enter Age"
/>
</label>
<button
onClick={e => handelSubmit(e)}
type="submit"
>
Update
</button>
<Link
to='/'
>
<button>
Home
</button>
</Link>
</form>
</div>
);
};