...

/

Incorporating the Config Component HousesUpdate

Incorporating the Config Component HousesUpdate

Learn how to use React Hooks, props, and event handlers to update components in React TypeScript.

Creating the HousesUpdate component

To create the HousesUpdate component that will enable us to update a house from the frontend of our real estate web application, we'll create a file named HousesUpdate.tsx inside the already-created config folder of the src folder of our project directory. In this file, we'll add the following lines of code:

Press + to interact
import React, {
PropsWithRef,
SyntheticEvent,
useEffect,
useState,
} from 'react';
import Wrapper from './config/Wrapper';
import { Redirect } from 'react-router-dom';
import { House } from './interfaces/house';
const HousesUpdate = (props: PropsWithRef<any>) => {
const [name, setName] = useState('');
const [image, setImage] = useState('');
const [description, setDescription] = useState('');
const [redirect, setRedirect] = useState(false);
useEffect(() => {
(async () => {
const response = await fetch(
`{{EDUCATIVE_LIVE_VM_URL}}/api/houses/${props.match.params.id}`
);
const house: House = await response.json();
setName(house.name);
setImage(house.image);
setDescription(house.description);
})();
}, []);
const submit = async (e: SyntheticEvent) => {
e.preventDefault();
await fetch(`{{EDUCATIVE_LIVE_VM_URL}}/api/houses/${props.match.params.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
image,
description,
}),
});
setRedirect(true);
};
if (redirect) {
return <Redirect to={'/config/houses'} />;
}
return (
<Wrapper>
<form onSubmit={submit}>
<div className='form-group'>
<label>Name</label>
<input
placeholder='Name'
type='text'
className='form-control'
name='name'
defaultValue={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className='form-group'>
<label>Image</label>
<input
placeholder='Name'
type='text'
className='form-control'
name='image'
defaultValue={image}
onChange={(e) => setImage(e.target.value)}
/>
</div>
<div className='form-group'>
<label>Description</label>
<input
placeholder='Description'
type='text'
className='form-control'
name='description'
defaultValue={description}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
<button className='btn btn-outline-secondary'>Save</button>
</form>
</Wrapper>
);
};
export default HousesUpdate;
  • Lines 1–6: We import React, PropsWithRef, syntheticEvent, useEffect, and useState from react.

  • Line 7: We import the Wrapper from the config folder in the src folder. ...