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

272
Vistas
Ensuring React reducer updates state before calling another function dependent on state

I've setup a global context and reducer for React, and created the functions auth.setCodeChallenge() and auth.setAuthURL(). These functions use the reducer to update the state, and the latter function is dependent on the state being updated before being called.

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
            }
        });
    }

However, upon calling the functions in order, I'm discovering that the latter function does not wait until the state is updated (i.e. is not working with the new state).

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

I confirmed that this was the issue because I tried replacing the reducer with code that directly alters the state, and it worked perfectly. I realize that this is not good practice, so I want to find a solution that works and is good practice.

about 4 years ago · Juan Pablo Isaza
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