Home > Net >  Issue with react redux and reducer
Issue with react redux and reducer

Time:04-05

I'm new in react-redux, and I have a problem with communication between reducer and store.

This is the idea on which I base:

I have a component "Login", that contains a button and two text inputs, and when i click that, I send the action to the reducer. Then, I update the state, and send it to the UI again (thats the way i understand the logic, correct me if i'm wrong). The problem occurs in the reducer, it never enter there, but yes in the action file (tested with console.logs). Maybe the connect is not working? or is in the store part?

Here I detach how I did it

action.js, with two operations only

const logout = () => {
 return {
 type: "USER_LOGOUT",
 payload: false,
};
};

const login = () => {
 return {
type: "USER_LOGIN",
payload: true,
};
};

export { logout, login };

reducer.js implementation, only change one boolean value

const initialState = {
logged: false,
};

export default (state = initialState, action) => {
 if (action.type === "USER_LOGOUT") {
  return {
   ...state,
   logged: false,
 };
}

if (action.type === "USER_LOGIN") {
 return {
   ...state,
   logged: true,
 };
}

return state;
};

index.js (store), here's how i declare the store part

import { createStore, combineReducers } from "redux";
import loginReducer from "./reducer";

const reducers = combineReducers({
loginReducer,
});

const store = createStore(reducers);

export default store;

Login.js, only the touchable part

import { logout, login } from "../redux/actions";

import { connect } from "react-redux";

...

connect(null, { logout, login }, Login);

...

<TouchableOpacity>
 ...
 onPress={() => checkValidation()}
 ...
</TouchableOpacity>

Here checkValidation, who calls the action "login"

checkValidation() =>

...
login();
...

CodePudding user response:

You are not dispatching the action. To make Redux aware of an action you must dispatch it.

If you are using a class component you need to connect the component and pass it the dispatch action from redux.

I suggest you to use the hooks because its way easier.

1-Import the useDispatch hook

import { useDispatch } from "react-redux";

2-Create the dispatch:

const dispatch = useDispatch();

3-Dispatch your action: checkValidation() =>

...
// Since your function login already returns the action object:
    dispatch(login());
...
  • Related