Debanjan Tewary
Debanjan Tewary

Reputation: 129

React Conditional state update not working

I am trying to create a form where user can create course paid/free , If paid then choose the price but if free price=0,

enter image description here

This is my default state:

  const [values, setValues] = useState({
    name: "",
    description: "",
    category: "",
    price: 500,
    paid: true,
    uploading: false,
    loading: false,
  });

Problem: If I click paid course my default price is 500 , which is the first price of the price list. But when I change to Free Course, state changes to "paid:false" but last selected price stayed like the picture below

enter image description here

Any Idea how to change! I have tried a few ways but nothing worked. Please help thank you❤️

I have tried to change it before sending it to backend, still didn't work.

const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if(values.paid == false) {
        setValues({...values, price: 0})
      }
      const { data } = await axios.post("/api/course/create-new-course", {
        ...values,
        image,
      });
      router.push("/instructor");
      toast.success("Continue adding lessions");
    } catch (err) {
      console.log(err);
      toast.error(err.response.data);
    }
  };


Upvotes: 3

Views: 871

Answers (2)

Saeed Shamloo
Saeed Shamloo

Reputation: 6554

Try to update your paid field in the CreateCourseForm like this:

 <select
      value={values.paid ? '1' : '0'}
      onChange={(e) => {
        const isPaid = e.target.value == '1';
        setValues({ ...values, price: isPaid ? 500 : 0 , paid: isPaid })
      }}
      className="select select-bordered select-secondary w-full lg:w-4/5 mb-3 rounded-none lg:rounded-lg"
    >
      <option value={'0'}>
        Free Course
      </option>
      <option value={'1'}>₹ Paid Course</option>
    </select>

Upvotes: 2

Muhammed Rahif
Muhammed Rahif

Reputation: 658

Calling setState() in React is asynchronous, for various reasons (mainly performance). Under the covers React will batch multiple calls to setState() into a single state mutation, and then re-render the component a single time, rather than re-rendering for every state change.

Fortunately, the solution is rather simple - setState accepts a callback parameter:

So try this :-

const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if(values.paid == false) 
        setValues(prevValues => ({...prevValues, price: 0}));
      
      const { data } = await axios.post("/api/course/create-new-course", {
        ...values,
        image,
      });
      router.push("/instructor");
      toast.success("Continue adding lessions");
    } catch (err) {
      console.log(err);
      toast.error(err.response.data);
    }
  };

Upvotes: 0

Related Questions