Search code examples
reduxredux-thunkredux-toolkit

converting to redux tool kit and getting "Unhandled Rejection (TypeError): state.push is not a function"


i'm stuck while converting an old project to redux tool kit getting an "Unhandled Rejection (TypeError): state.push is not a function" error. i haven't got to grips with the action/thunk and reducer immutability yet. The alerts are working but then the error msg.

import axios from 'axios';
import { setAlert } from '../alerts/alertSlice';

const slice = createSlice({
  name: 'auth',
  initialState: {
    token: localStorage.getItem('token'),
    isAuthenticated: null,
    loading: true,
    user: null,
  },
  reducers: {
    registerSuccess: (state, action) => {
      const { payload } = action.payload;
      state.push({
        payload,
        isAuthenticated: true,
        loading: false,
      });
    },
    registerFail: (state, action) => {
      localStorage.removeItem('token');
      state.push({
        token: null,
        isAuthenticated: false,
        loading: false,
        user: null,
      });
    },
  },
});

const { registerSuccess, registerFail } = slice.actions;

export default slice.reducer;

// Register User
export const register =
  ({ name, email, password }) =>
  async (dispatch) => {
    const config = {
      headers: {
        'comtent-Type': 'application/json',
      },
    };

    const body = JSON.stringify({ name, email, password });

    try {
      const res = await axios.post('/api/users', body, config);

      dispatch({
        type: registerSuccess,
        payload: res.data,
      });
    } catch (err) {
      const errors = err.response.data.errors;

      if (errors) {
        errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
      }

      dispatch(registerFail());
    }
  };

Solution

  • .push is an array function to add a new item at the end of an array - your state is not an array.

    You probably wanted to do something along the lines of

            state.token = null
            state.isAuthenticated = false
            state.loading = false
            state.user = null