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 badges
Add a comment  | 

1 Answer 1

Reset to default 2

The 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