skip to Main Content

I have a login component, a verification component and a userSlice file which has createAsyncThunk.

userSlice.js:

export const loginUser = createAsyncThunk(
  'users/login',
  async ({ email, password }, thunkAPI) => {
    try {
      const response = await fetch(
        'my_url',
        {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            email,
            password,
          }),
        }
      );
      let login_response = await response.json();
      console.log('response login', login_response);
      if (response.status === 200) {
        console.log('success from here')
        // localStorage.setItem('token', data.token);
        return login_response;
      } else {
        return thunkAPI.rejectWithValue(data);
      }
    } catch (e) {
      console.log('Error', e.response.data);
      thunkAPI.rejectWithValue(e.response.data);
    }
    return login_response;
  }
);

Here I get a response back when I post data. I have named it as login_response.
I simply need to pass it to my verification component.
I searched for it online but I did not understand the solutions which were there.

In my verification component I have imported loginUser like so

import { loginUser } from '../features/user/userSlice';

I know that loginUser has returned login_response. Now how do I access login_response in the verification component ?

2

Answers


  1. I guess you can access it using :

    
    // Then, handle actions in your reducers:
    const usersSlice = createSlice({
      name: 'users',
      initialState,
      reducers: {
        // standard reducer logic, with auto-generated action types per reducer
      },
      extraReducers: (builder) => {
        // Add reducers for additional action types here, and handle loading state as needed
        builder.addCase(loginUser.fulfilled, (state, action) => {
          // Add user to the state array
          state.entities.push(action.payload)
        })
      },
    })
    
    // Later, dispatch the thunk as needed in the app
    dispatch(loginUser(123))
    

    according to doc at https://redux-toolkit.js.org/api/createAsyncThunk :

    createAsyncThunk returns a standard Redux thunk action creator. The thunk action creator function will have plain action creators for the pending, fulfilled, and rejected cases attached as nested fields.

    Login or Signup to reply.
  2. const usersSlice = createSlice({
      name: 'users',
      initialState: {
        userData: []
      },
      reducers: {
        // standard reducer logic, with auto-generated action types per reducer
      },
      extraReducers: (builder) => {
        
        builder.addCase(loginUser.fulfilled, (state, action) => {
          // Add user to the state
          state.userData.push(action.payload)
        })
      },
    })
    

    now you can access it in your verification component

    do not forger to export slice and add it to your store

    and then in verification component:

    const user_data = useSelector(state => state.users.userData)
    

    console.log it to verify if you are getting right data.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search