Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
Saving the state of the function

I have two input text fields where I want to update them automatically using state. But whenever I uncheck the box, the value is disappearing. Once entered it should be there if I uncheck as well. If not, I cannot write two different values in the input text field.

import "./styles.css";
import { Jsme } from "jsme-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { default as FormData } from "form-data";

export default function App() {
  // I added the following state variables to keep track of checkboxes
  const [isCheckbox1Checked, setIsCheckbox1Checked] = useState(false);
  const [isCheckbox2Checked, setIsCheckbox2Checked] = useState(false);
  const [input1, setInput1] = useState("");
  const [input2, setInput2] = useState("");
  const [syncToFirst, setSyncToFirst] = useState();
  const [solutestate, setSoluteState] = useState();
  const { register, handleSubmit, control } = useForm({
    defaultValues: {
      solute: "",
      solvent: ""
    }
  });
  return (
    <div className="App">
      <Jsme
        height="300px"
        width="400px"
        options="oldlook,star"
        onChange={setSoluteState}
      />
      <h1>{solutestate}</h1>
      <input
        className="mr-2 leading-tight"
        type="checkbox"
        value={isCheckbox1Checked}
        onChange={() => setIsCheckbox1Checked(prev => !prev)}
      />
      <input
        className="mr-2 leading-tight"
        type="checkbox"
        value={isCheckbox2Checked}
        onChange={() => setIsCheckbox2Checked(prev => !prev)}
      />
      <form>
        <input
          {...register("solute")}
          placeholder="SOLUTE"
          onChange={(e) =>
            syncToFirst === 1
              ? setSoluteState(e.target.value)
              : setInput1(e.target.value)
          }
          value={isCheckbox1Checked ? solutestate : input1}
        />
        <input
          {...register("solvent")}
          placeholder="SOLVENT"
          onChange={(e) =>
            syncToFirst === 2
              ? setSoluteState(e.target.value)
              : input2(e.target.value)
          }
          value={isCheckbox2Checked ? solutestate : input2}
        />
      </form>
    </div>
  );
}

need a handler to save the state when the text changes. so that if I uncheck the check box the previous state is present in the input field text. and whenever i try to type directly in the second input text field it is throwing an error as input2 is not a function. code sand box link

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First of all input2(e.target.value) is not a function. Maybe you meant setInput2(e.target.value).

Secondly you set the value of syncToFirst as undefined. So the statement

 syncToFirst === 1
      ? setSoluteState(e.target.value)
      : setInput1(e.target.value)

goes into the else or : part which set its value to "" again as e.target.value is "". Hope that answers your question.

Edit:

Explaining further when the first checkbox is picked, the value of syncToFirst is 1. Now when you type something in the first checkbox, you call this method setSoluteState but the value of the input1 as a single source of truth is "". So when you uncheck this field, syncToFirst becomes 2. Now value become input1 as you have given. But input1 is "" so it becomes empty. The other text field however takes up the value of solute state and it goes up. Now when you type in the first input1 field, it will change its value.

This is expected behavior nothing off. You should work on your logic or DM me. Remember that in react the JSX part is re-rendered and the value field is calculated. Write it down and you'll see when actually the value of input1 and input2 are changing and what you are assigning in each re-render.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda