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

134
Vistas
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 Respuestas
Responde la pregunta

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 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