Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot read property 'pending' of undefined in the redux toolkit while using createAsyncThunk and createSlice (@reduxjs/toolkit": "^1.4.0)

I am getting the above-mentioned error on just adding the extraReducer to my createSlice.

This is a react-native application

Here is my code:

    export const login = createAsyncThunk(
      'loginAuth/login',
      async ({username, password}) => {
        try {
          const res = await api.post('SomeApi', {
            username,
            password,
          });
         
          return res.data;
        } catch (e) {
          return console.error(e.message);
        }
      },
    );

    const loginSlice = createSlice({
      name: 'loginAuth',
      initialState: {
        loginStatus: false,
        isLoading: false,
        error: '',
      },
      reducers: {
        //Yet to be filled
      },
      extraReducers: {
        [login.pending]: (state) => {
          state.isLoading = true;
        },
        [login.fulfilled]: (state, action) => {
          state.isLoading = false;
        },
        [login.rejected]: (state, action) => {
          state.error = action;
        },
      },
    });

Here is my dispatch code from another file:

    class Login extends Component {
      state = {
        data: {
          username: '',
          password: '',
        },
        textHidden: true,
      };
    
      handelSubmit = (status) => {
        if (status) {
          this.props.login(this.state.data);
        }
      };
    render(){
        return(
    //The UI for Input is here. I confirmed that the dispatch is working fine. I did log the username and password. But I didn't use the createAsyncThunk
    )
    }
    
    const mapDispatchToProps = (dispatch) => ({
      login: (data) => dispatch(login(data)),
    });
    
    export default connect(null, mapDispatchToProps)(Login);

To confirm the dispatch I did write another function with the same name login() where I logged the username and password:

    export const login = ({username, password}) => async (dispatch) => {
      console.log(username,password); // Here the dispatch is working fine
      //  called that API and dispatched to a reducer dispatch(loginSucess(result.data))
        };

With the above mention function, I did call the API and checked for success. It worked fine. I had to write a reducer for the loginSucess to cross-check if the API was working properly or not. And It did work properly

I am not understanding where I am going wrong!!

Need Help!!

This is the screenshot of the error:

enter image description here

like image 767
Satyam Avatar asked Dec 08 '20 06:12

Satyam


1 Answers

I got the answer. You check the same here. It was my foolishness. I had not arranged the code properly. The login should have been been on top of loginSlice. Thank you!!

like image 123
Satyam Avatar answered Nov 10 '22 21:11

Satyam