Home > Net >  Is there any method to change the value of input field in ReactJS?
Is there any method to change the value of input field in ReactJS?

Time:10-12

I am getting default input fields values( which takes data from the API) and then updating some them an again posting the data to the back end by API. But when i am sending the data to the Back end again only those values are appearing which are updated by me. The rest of values are showing null as they are not taking the default values.

Here is my code:

export default function ReferralPayment() {
const [data, setData] = useState({});
const [member,setMember]=useState({ RefPerLVL1:"",RefPerLVL2:"",RefPerLVL3:"",RefPerLVL4:"",RefPerLVL5:"",RefPerLVL6:"",RefPerLVL7:"",RefPerLVL8:"",RefPerLVL9:"",RefPerLVL10:"",RefPerLVL11:"",RefPerLVL12:""
      })
 var name,value;
    const handleInputs=e=>{
      name=e.target.name;
      value=e.target.value;
      setMember({...member,[name]:value})
    }
 const postData=async (e)=>{
      const {RefPerLVL1,RefPerLVL2,RefPerLVL3,RefPerLVL4,RefPerLVL5,RefPerLVL6,RefPerLVL7,RefPerLVL8,RefPerLVL9,RefPerLVL10,RefPerLVL11,RefPerLVL12}=member;
     const res=await fetch("/refpaypost",{
       method:"POST",
       headers:{
         "Content-Type":"application/json"
       },
       body:JSON.stringify({
        RefPerLVL1,RefPerLVL2,RefPerLVL3,RefPerLVL4,RefPerLVL5,RefPerLVL6,RefPerLVL7,RefPerLVL8,RefPerLVL9,RefPerLVL10,RefPerLVL11,RefPerLVL12
       })
     });
     const data=await res.json();
        }
  useEffect(() => {
        async function fetchBooks() {
          const response = await fetch('/refpayget');
          const json = await response.json();
          setData(json.rf2);
          console.log(json.rf2)
      }
      fetchBooks();
     
  },[]);
   if (!data.length) {
    return null;
  }
 return (
 <Form >
              <Row >
                  <Col ><Form.Text className="text-muted">LVL1 Payment Percentage</Form.Text></Col>
                  <Col><Form.Control size="sm" type="text" name="RefPerLVL1" placeholder="Enter Amount" autoFocus defaultValue={data[0].RefPerLVL1} onChange={e=>handleInputs(e)}/></Col>
              </Row>
              <Row >
                  <Col ><Form.Text className="text-muted">LVL2 Payment Percentage</Form.Text></Col>
                  <Col><Form.Control size="sm" type="text" name="RefPerLVL2" placeholder="Enter Amount" defaultValue={data[0].RefPerLVL2} onChange={e=>handleInputs(e)}/></Col>
              </Row>
              <Row >
                <Col ><Form.Text className="text-muted">LVL3 Payment Percentage</Form.Text></Col>
                  <Col><Form.Control size="sm" type="text" name="RefPerLVL3" placeholder="Enter Amount" defaultValue={data[0].RefPerLVL3} onChange={e=>handleInputs(e)}/></Col>
              </Row>
</Form>
 <Button variant="dark" onClick={()=>postData()}>
                Save Changes
              </Button>

If i didn't click on the input field, it doesn't changed and the value appear to be null as the member usestate have by default null values. So how can I just use the default values of input fields when i didn't change the input fields? If I try to initialise the member usestate with data usestate, how can i do it?

CodePudding user response:

Sounds like you are more wanting fully controlled inputs over the uncontrolled inputs you currently have. The issue with using the defaultValue prop and not referencing the form when submitting is that the member state isn't updated until the onChange handler is triggered by.... changing the input's value. If the input is never changed then the updated value is never saved into state and used later.

To convert, first save your fetched "default" values into local state, and second, swap the defaultValue prop to the value prop so the inputs are controlled from the React state.

useEffect(() => {
  async function fetchBooks() {
    const response = await fetch('/refpayget');
    const json = await response.json();
    setMember(json.rf2[0]); // <-- save the first array elements values
  }
  fetchBooks();
},[]);

...

<Form.Control
  size="sm"
  type="text"
  name="RefPerLVL1"
  placeholder="Enter Amount"
  autoFocus
  value={member.RefPerLVL1} // <-- switch to value prop, reference member state
  onChange={handleInputs}
/>
// ... repeat for other Form.Control inputs
  • Related