'Dispatch clear all my data form input reactjs
I use reactjs. But when I handle onClick event. After I clicked on Button and dispatch an event. It's clear all my data in Input. I don't know why the data is cleared and how can prevent it.
import React, { useEffect } from "react";
import { Input, Form, Checkbox, Button, Row, Col, notification } from "antd";
import { loginRequest } from "../../../store/userStore";
import { useDispatch, useSelector } from "react-redux";
export default function SignInPage() {
const dispatch = useDispatch()
const handleSubmit = (e) => {
dispatch(loginRequest());
}
return (
<>
<Input>
</Input>
<Input>
</Input>
<Button onClick={() => {
handleSubmit()
}}>Click</Button>
</>
)
}
Solution 1:[1]
Issue
I'm guessing these inputs and button are being rendered with a form element and you aren't preventing the default form action from occurring. Button elements have a type="submit" by default, so when clicked will invoke the default form action and reload the page (clearing the inputs).
Solution
Call preventDefault on the event object.
const handleSubmit = (e) => {
e.preventDefault(); // <-- prevent the default
dispatch(loginRequest());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Drew Reese |
