简体   繁体   中英

State not changing after update

I have a problem with use state component of property where the state does not change when loading component. The state of the item should change since i am updating it after receiving a response in the previous form stepper but when i add a new dynamic input field, it changes the state but not for the first one在此处输入图像描述

Here is the code that is bringing the error

export default function AddProp() {
   const [propertyID, setPropertyID] = useState(0);   
   const [step,setStep] = useState(1);   
   const [values,setValues] = useState({  
    responseMessage: "",
    loading: false,
    name: "",
    address: "",
    county: "",
    city: "",
    zipcode: "",
    type: "",
    specifictype: "",})

  const [formValues, setFormValues] = useState([
    { number_of_units: "", market_rent: "", square_feet: "", beds: "", property:propertyID.property },
  ])

  let addFormFields = () => {
    setFormValues([
      ...formValues,
      {  number_of_units: "", market_rent: "", square_feet: "", beds: "" ,property:propertyID.property},
    ]);
  };
   
  let sendProperties = async () => {
    
    const response = await axios
      .post(
        "http://127.0.0.1:8000/property/api/v1/addProperty/",
        {
          property_name: values.name,
          address: values.address,
          county: values.county,
          city: values.city,
          zipcode: values.zipcode,
          property_type: values.type,
        },
        { headers: headers }
      );
      setPropertyID(response.data);
      if(response.status == 200){        
        setStep(step + 1 );
      }else{
        alert("An error occurred");
      }
        

    
  };

  
  switch (step) {   
    case 3:
      return (
        <PropertyType
        values={formValues}
        handleChange={handleFormChange}
        add={addFormFields}
        remove={removeFormFields}
        prevStep={prevStep}
        nextStep={getandSend}
      />
      );
      case 4:
        return <Success message={"DONE"} />;

      default:
    }
}
  

Instead of using the current formValues , pass a callback to setFormValues that takes in one parameter, say currentFormValues , and use that to update the state instead.

const addFormFields = () => {
    setFormValues(currentFormValues => [
      ...currentFormValues,
      {  number_of_units: "", market_rent: "", square_feet: "", beds: "" ,property:propertyID.property},
    ]);
  };

This problem is related to stale state, a problem that occurs whenever we're trying to update state, often within a closure .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM