1
votes

This really confuses me. I created a reducer and an action in my react-native app. But the reducers switch doesn't match the type and just returns the default state. The whole store.js, I'm using redux-persist to store redux data in to the AsyncStorage:

import {AsyncStorage} from 'react-native';
import {createStore, applyMiddleware} from 'redux';
import {createLogger} from 'redux-logger';
import thunk from 'redux-thunk';
import {persistStore, persistReducer} from 'redux-persist';
import {initAxios, configAxios} from './axios';
import {LOGIN, LOGOUT, LOGIN_ERROR} from '../components/login/actions';

const initialState = {
    loggedIn: false,
    token: '',
};

const globalReducer = (state = initialState, {type, payload}) => {
    console.warn(type); // Logs: LOGIN
    switch (type) {
        case LOGIN:
            console.warn('update state'); // doesn't log
            return {...state, loggedIn: true, token: payload};
        case LOGOUT:
            return {...state, loggedIn: false, token: ''};
        case LOGIN_ERROR:
            return {...state, loginError: payload, loggedIn: false};
        default:
            console.warn('no state update'); // do logs
            return state;
    }
};

const persistConfig = {
    key: 'root',
    storage: AsyncStorage,
    whitelist: ['loggedIn', 'token'],
};

const persistedReducer = persistReducer(persistConfig, globalReducer);

const axiosInstance = initAxios();

export const store = createStore(
    persistedReducer,
    applyMiddleware(
        createLogger(),
        thunk.withExtraArgument({axios: axiosInstance}),
    ),
);

configAxios(axiosInstance, store.dispatch);

export const persistor = persistStore(store);

and the action that is dispatched:

export const loginUser = (login, password, navigate) => async (
    dispatch,
    _,
    {axios},
) => {
    try {
        const response = await axios.post('/login', {
            login,
            password,
        });
        if (!response.token) {
            throw new Error('Wrong login credentials');
        }
        dispatch({type: LOGIN, payload: response.token});
        navigate();
    } catch (error) {
        console.error(error.message);
        dispatch({type: LOGIN_ERROR, payload: error.message});
    }
};
1
It's just const LOGIN = 'LOGIN'; - SnakesCantWearBoots
I remember having the exact same problem But I forgot what caused her - Yoel
Maybe some dependency? I saw that was the case in some github issue. But it was react-router which I don't use - SnakesCantWearBoots
no ,It's in your code - Yoel
I've added the whole store creation file, maybe there is something I can't see - SnakesCantWearBoots

1 Answers

2
votes

You don't export the types

   export const LOGIN = 'LOGIN';