Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

271
Views
Asegurar el estado de las actualizaciones del reductor React antes de llamar a otra función dependiendo del estado

Configuré un contexto global y un reductor para React, y creé las funciones auth.setCodeChallenge() y auth.setAuthURL(). Estas funciones usan el reductor para actualizar el estado, y la última función depende de que el estado se actualice antes de ser llamado.

 function AuthContextProvider(props) { const [auth, setAuth] = useState({ codeChallenge: null, authURL: null, authCode: null, token: null }); //const history = useHistory(); useEffect(() => { }, []); const authReducer = (action) => { const{type, payload} = action; switch(type) { case AuthActionType.SET_CODE_CHALLENGE: { console.log(payload.codeChallenge); return setAuth({ codeChallenge: payload.codeChallenge }) } case AuthActionType.SET_AUTH_URL: { console.log(payload.authURL); return setAuth({ authURL: payload.authURL }) } case AuthActionType.SET_AUTH_CODE: { return setAuth({ authCode: payload.authCode }) } case AuthActionType.STORE_TOKEN: { return setAuth({ codeChallenge: null, authURL: null, authCode: null, token: payload.token, }) } default: return auth; } } auth.setCodeChallenge = async function() { let response = await fetch('/code_challenge'); let data = await response.text(); data = data.replace(/"/g,""); authReducer({ type: AuthActionType.SET_CODE_CHALLENGE, payload: { codeChallenge: data } }); } auth.setAuthURL = async function() { let response = await fetch(`/authorization_url/${auth.codeChallenge}`) let data = await response.text(); authReducer({ type: AuthActionType.SET_AUTH_URL, payload: { authURL: data } }); }

Sin embargo, al llamar a las funciones en orden, descubro que la última función no espera hasta que se actualice el estado (es decir, no funciona con el nuevo estado).

 async function handleLogin() { await auth.setCodeChallenge(); console.log(auth.codeChallenge); await auth.setAuthURL(); // Not working with updated state. console.log(auth.authURL) }

Confirmé que este era el problema porque intenté reemplazar el reductor con un código que altera directamente el estado y funcionó perfectamente. Me doy cuenta de que esto no es una buena práctica, por lo que quiero encontrar una solución que funcione y sea una buena práctica.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!