I have some problem with updating the editModal (react bootstrap modal). after dispatching the action it works and I'm able to fetch single pet data as an object. and redux dev tools confirms that But modal doesn't open at first attempt and I need to click the (edit button: doesn't matter which one) again to show filled input data ,and each time I click the edit button for first pet or second pet it doesn't update modal and it shows data related to the previously clicked edit and as you see I clicked the second edit and data has fetched as redux dev tools shows correctly but Modal still shows first pet details
thanks for your help :)
here's my code
const PetScreen = () => {
const dispatch = useDispatch()
//part of state that comes from store.js
const petDetailByUser = useSelector((state) => state.petDetailByUser)
//when action dispatch petDetails fills with single pet Details ex:_id,editPetName,...
const { petDetailLoading, petDetails } = petDetailByUser
const [editPetName, setEditPetName] = useState('')
//edit button dispatch getPetDetail and get pet data as an object
const editButtonHandler = (id) => {
dispatch(getPetDetails(id))
if (petDetails) {
setEditPetName(petDetails.editPetName)
//shows edit modal
handleEditShow()
}
}
//this field is inside react modal body
<Form.Control
type='text'
placeholder='Pet Name'
name='editPetName'
value={editPetName}
onChange={(e) => setEditPetName(e.target.value)}
>
</Form.Control>
Just after dispatch(getPetDetails(id))
, the editPetName
variable has not been refreshed yet so it contains the name of the previous pet.
You can fix it by using an effect to update editPetName
when petDetails
is updated.
const petDetailByUser = useSelector((state) => state.petDetailByUser)
const { petDetailLoading, petDetails } = petDetailByUser;
const [editPetName, setEditPetName] = useState('');
useEffect(() => {
if (petDetails) {
setEditPetName(petDetails.editPetName);
handleEditShow();
}
}, [petDetails]);
const editButtonHandler = (id) => dispatch(getPetDetails(id));