Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
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);
    }
  };


about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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>
about 4 years ago · Juan Pablo Isaza Denunciar

0

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);
    }
  };
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda