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.