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.