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

133
Visualizações
Create and update React state via custom hook function

I have a async function in a custom hook which should update the state but it doesn't

export const useXYZ = () => {
    const [XYZ, setXYZ] = useState([])
    const update = () => {
        BackendService.getAllXYZ().then(
            ({data}) => {
//------------>>> here I want to update, but if I use the hook it doesnt update if I call update()
                setXYZ(data)
            }
        ).catch((error)=>{
        })
    }
    return [XYZ, update]
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Here is a minimal complete example of a custom hook with asynchronous state update and how it can be used in your component.

function App() {
  const [d1, roll1] = useDice(6)
  const [d2, roll2] = useDice(20)
  const [d3, roll3] = useDice(8)
  return <div>
    <button type="button" onClick={roll1} children={d1 || "roll"} />
    <button type="button" onClick={roll2} children={d2 || "roll"} />
    <button type="button" onClick={roll3} children={d3 || "roll"} />
    <pre>{JSON.stringify([d1, d2, d3], null, 2)}</pre>
  </div>
}

function useDice(sides = 6) {
  const [value, setValue] = React.useState(null)
  return [
    value,
    event => {
      setValue("...")
      setTimeout(_ => setValue(Math.floor(Math.random() * sides) + 1), 1000)
    }
  ]
}

ReactDOM.render(<App/>, document.querySelector("#app"))
button {
  width: 3rem;
  line-height: 3rem;
  margin: 0 0.5rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>

Custom hooks can return any number of values of any type. Consider this alternative abstraction that returns a value and a component without the need to assign event handlers.

function App() {
  const [value1, d1] = useDice(6)
  const [value2, d2] = useDice(20)
  const [value3, d3] = useDice(8)
  return <div>
    {d1} {d2} {d3}
    <pre>{JSON.stringify([value1, value2, value3], null, 2)}</pre>
  </div>
}

function useDice(sides = 6) {
  const [value, setValue] = React.useState(null)
  function roll(event) {
    setValue("...")
    setTimeout(_ => setValue(Math.floor(Math.random() * sides) + 1), 1000)
  }
  return [
    value,
    <button type="button" onClick={roll} children={value || "roll"} />    
  ]
}

ReactDOM.render(<App/>, document.querySelector("#app"))
button {
  width: 3rem;
  line-height: 3rem;
  margin: 0 0.5rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>

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