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

328
Visualizações
ReactJS: Save button value on submit

I have created a form, and I have two submit button. Now i'm trying to save the value from the button to make two different api call based precisely on the value of the button.

My problem is that sometimes the value from the button results "undefined" so when it is clicked nothing happend.

 return (
              <AvForm model={{}} onSubmit={saveEntity}>
    //.....
    <Button id="pdf" replace color="info" data-cy="entityCreatePDF" type="submit" onClick={buttonClicked} value="pdf">
                      <FontAwesomeIcon icon="save" />
                      &nbsp;
                      <span className="d-none d-md-inline"> PDF </span>
                    </Button>
                    &nbsp;
                    <Button color="primary" id="csv" data-cy="entityCreateCSV" type="submit" onClick={buttonClicked} value="csv">
                      <FontAwesomeIcon icon="save" />
                      &nbsp;<span className="d-none d-md-inline"> CSV </span>
                    </Button>
    
    )

  const buttonClicked = event => {
    console.log('event target', event.target.value);
    setButtonClick(event.target.value);
  };

  const saveEntity = (event, errors, values) => {
//....
 filteredEntities(params, sorting)
}


const filteredEntities = (params, sort) => {
    console.log('-- buttonClick --', buttonClick);
// there sometimes I receive undefined and so it doesn't enter in the if
    if (buttonClick === 'pdf') {
      getReportPDF(params, sort);
    }
    if (buttonClick === 'csv') {
      getReportCSV(params, sort);
    }
}

There is something that I should doing to avoid this behavior (i.e. that the key results in an undefined value and therefore does not allow me to take any action?).

Thank you

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

0

Short answer:

Replace

  const buttonClicked = event => {
    console.log('event target', event.target.value);
    setButtonClick(event.target.value);
  };

with

  const buttonClicked = event => {
    console.log('event target', event.currentTarget.value);
    setButtonClick(event.currentTarget.value);
  };

Why? Sometimes you click the button itself, sometimes e.g. icon inside it - the element you click is actually a "target". "currentTarget" however allows the use of element the event listener was assigned to.

about 4 years ago · Juan Pablo Isaza Relatório

0

This issue might be arising from setState being asynchronous, ie, the state doesn't change immediately after setButtonClick is called. You can use a ref to sidestep this issue, if you don't need to re-render when buttonClick is changed, and use buttonClick.current to get the value.

const buttonClick = useRef();
...

const buttonClicked = event => {
    console.log('event target', event.target.value);
    buttonClick.current = event.target.value;
  };
...

const filteredEntities = (params, sort) => {
    console.log('-- buttonClick --', buttonClick.current);
    if (buttonClick.current === 'pdf') {
      getReportPDF(params, sort);
    }
    if (buttonClick.current === 'csv') {
      getReportCSV(params, sort);
    }
}

If you need to re-render when it changes, use both the state and a ref.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can directly save the value to the state. As it is not an input field, no need to deal with event.target.value

.....
<Button onClick={() => setButtonClick('csv')}
<Button onClick={() => setButtonClick('pdf')}
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