A
A
Alexey Yakovlev2021-01-16 14:18:13
redux
Alexey Yakovlev, 2021-01-16 14:18:13

Object not added to array?

Reducer loggedReducer:

export default function loggedReducer(state=[], action) {
    switch(action.type) {
        case 'SIGN_IN':
            return state.push(action.payload);
        case 'LOG_OUT':
            return state = [];
        default:
            return state;
    }
}


I get the user object:
const dispatch = useDispatch();

React.useEffect(() => {
      async function fetch() {
          const {data} = await axios.get('/profile/api/user');

          dispatch(signIn(data));
          
          setUser(data);
      }

      fetch();
  }, [dispatch]);


action:
export const signIn = (user) => {
    return {
        type: 'SIGN_IN',
        payload: user
    }
}


reducer:
import loggedReducer from './isLogged.js';
import {combineReducers} from 'redux';

const allReducers = combineReducers({
    logged: loggedReducer
})

export default allReducers;


Then in another component I output logged to the console:
const logged = useSelector(state => state.logged);
const dispatch = useDispatch();

console.log('logged: ' + logged); // 1


It is equal to 1, why is that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-01-16
@aleshaykovlev

The push array method returns the new size of the array. The reducer must return a new array, so the correct code
return [...state, action.payload]
instead of
return state.push(action.payload)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question