import React,{useState,useEffect} from 'react';
import { Button, Form } from 'semantic-ui-react';
import axios from 'axios';
import {useNavigate} from 'react-router';
import usePrevious from './prev';
import {Link} from 'react-router-dom';
const Update = () => {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [checkbox, setCheckBox] = useState(false);
const [id, setID] = useState(null);
let navigate = useNavigate();
Here I am storing the input field's previous value using another component to get the previous value
const previous = usePrevious(firstName);
useEffect(() => {
setID(localStorage.getItem('ID'));
setFirstName(localStorage.getItem('First Name'));
setLastName(localStorage.getItem('Last Name'));
setCheckBox(localStorage.getItem('Checkbox Value'))
}, []);
This is where the updated data is being sent to mock api and in if condition i am comparing previous value with new one(if it changes).
const updateApiData = () => {
axios.put(`https://61cb2af8194ffe0017788c01.mockapi.io/fakeData/${id}`,{
firstName,
lastName,
checkbox
}).then(()=>{
navigate('/read');
})
if(firstName==previous){
console.log("change");
}
}
return(
<div>
<Form>
<Form.Field>
<label>First Name</label>
<input id="i1" placeholder='First Name' value={firstName}
onChange={(e)=>setFirstName(e.target.value)}
/>
</Form.Field>
<Form.Field>
<label>Last Name</label>
<input placeholder='Last Name' value={lastName}
onChange={(e)=>setLastName(e.target.value)} />
</Form.Field>
here on button click i am calling the function of sending data to api. i need to check here if on click update the field's value is same as the previous one.
<Button type='submit' onClick={updateApiData}>Update</Button>
<Link to="/read">
<Button>Cancel</Button>
</Link>
</Form>
<br></br>
<Button onClick={()=>navigate(-1)}>Go Back</Button>
</div>
)
}
export default Update;