admin管理员组文章数量:1201982
I have this handler and function to update my react context but it's not updating. It does not dispatch the action
This function switches accounts
const loadAccountSwitch = useCallback(
async (accountId, userId, userRoleName) => {
if (!accountId || !userId || !userRoleName) return;
try {
setLoading(true);
const results = await getToken(accountId, userId, userRoleName);
const { user: apiUser,accessToken } = results.data;
setLoading(false);
if (!apiUser || typeof apiUser !== 'object' || !apiUser._id) {
console.error('Invalid apiUser:', apiUser);
return;
}
console.log('after account switch', apiUser);
console.log('isMountedRef',isMountedRef.current)
if (isMountedRef.current) {
handleClose();
dispatch({ type: 'UPDATE_USER',
payload: {
user: apiUser
}
});
}
navigate(`${PATH_DASHBOARD.general.app}`);
console.error('after navigating');
handleClose();
} catch (error) {
setLoading(false);
}
},
[dispatch, isMountedRef]
);
This function is the handler for the react context
const handlers = {
INITIALIZE: (state, action) => {
const { isAuthenticated, user } = action.payload;
return {
...state,
isAuthenticated,
isInitialized: true,
user,
};
},
LOGIN: (state, action) => {
const { user } = action.payload;
console.log('State before LOGIN:', state);
console.log('Payload in LOGIN:', user);
return {
...state,
isAuthenticated: true,
user,
};
},
UPDATE_USER: (state, action) => {
const { user } = action.payload;
return {
...state,
isAuthenticated: true,
user,
};
},
};
This is the Provider
function AuthProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
const initialize = async () => {}
initialize();
}, []);
const login = async (email, password) => {
const url = `${HOST_API}/sign`;
const response = await axios.post(url, {
email,
password,
});
if (!response || response?.data === undefined || response?.data?.code === 1) {
if (!response) {
throw new Error('Could not make request');
}
throw new Error(response.data?.message);
}
const { accessToken, user } = response.data.data;
setSession(accessToken);
dispatch({
type: 'LOGIN',
payload: {
user,
},
});
};
const contextValue = useMemo(
() => ({
...state,
method: 'jwt',
login,
}),
[state]
);
return (
<AuthContext.Provider value={contextValue}>
{children}
</AuthContext.Provider>
);
}
It runs the other codes in the account switch function but it particularly does not dispatch the action 'UPDATE_USER'
I have this handler and function to update my react context but it's not updating. It does not dispatch the action
This function switches accounts
const loadAccountSwitch = useCallback(
async (accountId, userId, userRoleName) => {
if (!accountId || !userId || !userRoleName) return;
try {
setLoading(true);
const results = await getToken(accountId, userId, userRoleName);
const { user: apiUser,accessToken } = results.data;
setLoading(false);
if (!apiUser || typeof apiUser !== 'object' || !apiUser._id) {
console.error('Invalid apiUser:', apiUser);
return;
}
console.log('after account switch', apiUser);
console.log('isMountedRef',isMountedRef.current)
if (isMountedRef.current) {
handleClose();
dispatch({ type: 'UPDATE_USER',
payload: {
user: apiUser
}
});
}
navigate(`${PATH_DASHBOARD.general.app}`);
console.error('after navigating');
handleClose();
} catch (error) {
setLoading(false);
}
},
[dispatch, isMountedRef]
);
This function is the handler for the react context
const handlers = {
INITIALIZE: (state, action) => {
const { isAuthenticated, user } = action.payload;
return {
...state,
isAuthenticated,
isInitialized: true,
user,
};
},
LOGIN: (state, action) => {
const { user } = action.payload;
console.log('State before LOGIN:', state);
console.log('Payload in LOGIN:', user);
return {
...state,
isAuthenticated: true,
user,
};
},
UPDATE_USER: (state, action) => {
const { user } = action.payload;
return {
...state,
isAuthenticated: true,
user,
};
},
};
This is the Provider
function AuthProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
const initialize = async () => {}
initialize();
}, []);
const login = async (email, password) => {
const url = `${HOST_API}/sign`;
const response = await axios.post(url, {
email,
password,
});
if (!response || response?.data === undefined || response?.data?.code === 1) {
if (!response) {
throw new Error('Could not make request');
}
throw new Error(response.data?.message);
}
const { accessToken, user } = response.data.data;
setSession(accessToken);
dispatch({
type: 'LOGIN',
payload: {
user,
},
});
};
const contextValue = useMemo(
() => ({
...state,
method: 'jwt',
login,
}),
[state]
);
return (
<AuthContext.Provider value={contextValue}>
{children}
</AuthContext.Provider>
);
}
It runs the other codes in the account switch function but it particularly does not dispatch the action 'UPDATE_USER'
Share Improve this question edited Jan 21 at 16:24 Drew Reese 203k17 gold badges234 silver badges266 bronze badges asked Jan 21 at 8:59 lutakynlutakyn 4741 gold badge7 silver badges22 bronze badges1 Answer
Reset to default 2The issue is that dispatch isn't included in the context value. Here's the fix
function AuthProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
const contextValue = useMemo(
() => ({
...state,
method: 'jwt',
login,
dispatch // Add dispatch to context
}),
[state]
);
return (
<AuthContext.Provider value={contextValue}>
{children}
</AuthContext.Provider>
);
}
本文标签: reactjsReact is not updating the Context and the ProviderStack Overflow
版权声明:本文标题:reactjs - React is not updating the Context and the Provider - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738642792a2104409.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论