I have two reducers which share some actions. Issue is when i dispatch action on one screen it triggers action on the other screen. Boths screen are in a TabNavigator therefore I can easily see that if I change a field on 1 screen the same field is changed on the other screen as well.
Reducer 1
import * as Actions from '../actions/Types';
const initialState = {
email: '',
password: ''
};
const signInReducer = (state = initialState, action) => {
switch(action.type) {
case Actions.CHANGE_EMAIL_INPUT:
return Object.assign({}, state,
{ email: action.email }
);
case Actions.CHANGE_PASSWORD_INPUT:
return Object.assign({}, state,
{ password: action.password }
);
default:
return state;
}
}
export default signInReducer;
Reducer 2
import * as Actions from '../actions/Types';
const initialState = {
firstName: '',
lastName: '',
email: '',
password: '',
repeatPassword: ''
};
const signUpReducer = (state = initialState, action) => {
switch(action.type) {
case Actions.CHANGE_FIRST_NAME_INPUT:
return Object.assign({}, state,
{ firstName: action.firstName }
);
case Actions.CHANGE_LAST_NAME_INPUT:
return Object.assign({}, state,
{ lastName: action.lastName }
);
case Actions.CHANGE_EMAIL_INPUT:
return Object.assign({}, state,
{ email: action.email }
);
case Actions.CHANGE_PASSWORD_INPUT:
return Object.assign({}, state,
{ password: action.password }
);
case Actions.CHANGE_REPEAT_PASSWORD_INPUT:
return Object.assign({}, state,
{ repeatPassword: action.password }
);
default:
return state;
}
}
export default signUpReducer;
Store
import { createStore, combineReducers } from 'redux';
import signInReducer from '../reducers/SignIn';
import signUpReducer from '../reducers/SignUp';
import profileReducer from '../reducers/Profile';
const rootReducer = combineReducers({
signIn: signInReducer,
signUp: signUpReducer,
profile: profileReducer
});
const configureStore = () => {
return createStore(rootReducer);
}
export default configureStore;
As you can see there are some common actions like CHANGE_EMAIL_INPUT & CHANGE_PASSWORD_INPUT and I dont want them to be triggered together. One way I can figure out is to change the name of actions and make then more specific to screen but this doesn't sound good. Another could be to wrap reducers so that we know what is being called but not getting an idea on the wrapper.
Any suggestions.
You should not reuse the same action name between 2 reducers, to avoid unintended effects, use different names.
For example
Actions.SIGNUP_ CHANGE_EMAIL_INPUT
and
Actions.SIGNIN_ CHANGE_EMAIL_INPUT
Otherwise, you can merge your 2 reducers, adding a state to know from which screen this change emerged.
well, i solved it by creating a wrapper for the reducers.
Store
function createNamedWrapperReducer(reducerFunction, reducerName) {
return (state, action) => {
const isInitializationCall = state === undefined;
const shouldRunWrappedReducer = reducerName(action) || isInitializationCall;
return shouldRunWrappedReducer ? reducerFunction(state, action) : state;
}
}
const rootReducer = combineReducers({
// signIn: signInReducer,
// signUp: signUpReducer,
// profile: profileReducer
signIn: createNamedWrapperReducer(signInReducer, action => action.name === 'signIn'),
signUp: createNamedWrapperReducer(signUpReducer, action => action.name === 'signUp'),
profile: createNamedWrapperReducer(profileReducer, action => action.name === 'profile'),
});
Screen
onChangeEmail: (email) => { dispatch({name: 'signIn', type: Actions.CHANGE_EMAIL_INPUT, email: email}) },
Related
Here is my action.js:
export const update = user => ({
type: 'UPDATE_USER',
payload: user,
});
Here is my reducer.js:
const initialState = {
name: '',
logo:'',
mobile:'',
};
export default (state = initialState, action) => {
const { type, payload } = action;
switch (type) {
case 'UPDATE_USER':
return {
...state,
user: payload.user,
};
default:
return state;
}
};
Here is my store.js:
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import userReducer from "../reducers/userReducer";
const middleware = [thunk];
const store = createStore(userReducer, applyMiddleware(...middleware));
export default store;
Here I am setting data:
let user = {
name: 'abcd',
logo: result.payload.data.logo,
mobile: '0123456789'
};
dispatch(update(user));
Trying to get the value in component
const state = useSelector((state) => state);
console.log('statevalue',state);
I am using Redux to store loggedIn user data to render with UI Component. After setting data the values in console printing empty. The user details is not updated. How can I fix this?
Note value in console
'statevalue', { name: '', logo: '', mobile: '', user: undefined }
Expected output:
'statevalue', { name: 'abcd', logo: 'https://lfkgjkfk', mobile: '0123456789'}
Update your reducer with this change -
case 'UPDATE_USER':
return {
...state,
...payload,
};
So i am working with redux and i wrote a reducer to manage todos;
import { combineReducers } from "redux";
import { ADD_TODO, COMPELETE_TODO, REMOVE_TODO } from "./actiontypes";
const initialState = {
todos: [],
};
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TODO:
return {
...state,
todos: [...state.todos, action.payload],
};
case COMPELETE_TODO:
case REMOVE_TODO:
return {
...state,
todos: state.todos.filter(
(todo) => state.todos.indexOf(todo) != action.payload
),
};
default:
return state;
}
};
export default combineReducers({
rootReducer,
});
As you can see that I created a reducer and user combineReducer and then passed it to store in other file and it is working fine.
Now how much I understood combineReducer is that it combines seperated reducers when we write them seperately. So if i change the above reducer (as i have only single reducer) to following;
import { ADD_TODO, COMPELETE_TODO, REMOVE_TODO } from "./actiontypes";
const initialState = {
todos: [],
};
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TODO:
return {
...state,
todos: [...state.todos, action.payload],
};
case COMPELETE_TODO:
case REMOVE_TODO:
return {
...state,
todos: state.todos.filter(
(todo) => state.todos.indexOf(todo) != action.payload
),
};
default:
return state;
}
};
export default rootReducer;
And pass this to the state but it gives error. It gives undefined when i try to access todos by using useSelector;
const {todos} = useSelector(state => ({
todos: state.rootReducer.todos
}))
So what i think is i didn't understood combineReducers properly. Please explain what is causing the error above.
Combine reducer adds namespaces to the state controlled by each reducer based on the keys of the object you pass in. When you don't use combine reducer, there won't be a namespace. So change state.rootReducer to state.
combineReducers creates a reducer that separates the state of the combined reducers. In the documentation they show this example:
rootReducer = combineReducers({potato: potatoReducer, tomato: tomatoReducer})
which would produce the following state object
{
potato: {
// ... potatoes, and other state managed by the potatoReducer ...
},
tomato: {
// ... tomatoes, and other state managed by the tomatoReducer, maybe some nice sauce? ...
}
}
Thus when you write
combineReducers({
rootReducer,
});
The state object will be
{
rootReducer: {
// rootReducer's state
}
}
In your second example you just return the rootReducer. Therefore there are no separate states. The rootReducer operates on the root state. Thus you must adjust the selection.
const {todos} = useSelector(state => ({
todos: state.todos
}))
Im implementing redux in my react native app, I need to create 2 reducers, one of them is designed to manage login state and the other to manage some process status.
Reducers:
isLogged
processStatus
processStatus Actions:
export function start() {
return {
type: 'START_LOADING'
}
}
export function stop() {
return {
type: 'END_LOADING'
}
}
isLogged Actions:
export function signIn() {
return {
type: 'SIGN_IN'
}
}
export function loadFinished() {
return {
type: 'LOAD_FINISHED'
}
}
export const signOut = userAuthParams => (
{
type: 'SIGN_OUT'
}
);
export const firstLogin = userAuthParams => (
{
type: 'FIRST_LOGIN'
}
);
export const fbLogin = userAuthParams => (
{
type: 'FB_LOGIN'
}
);
process Reducer:
const isLoading = (state = false, action) => {
switch (action.type) {
case 'START_LOADING':
return 1;
case 'END_LOADING':
return 0
default:
return 0
}
}
export default isLoading
isLogged Reducer
const isLogged = (state = false, action) => {
switch (action.type) {
case 'SIGN_IN':
return 2;
case 'LOAD_FINISHED':
return 1
case 'SIGN_OUT':
return -1
case 'FIRST_LOGIN':
return 3
case 'FB_LOGIN':
return 4
default:
return 0
}
}
export default isLogged
root Reducer:
import isLogged from './IsLoggedReducer'
import process from './ProcessReducer'
import { combineReducers } from 'redux'
const allReducers = combineReducers({
isLogged: isLogged,
processState: process
})
export default allReducers
store
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk';
import allReducers from './index'
const store = createStore(allReducers, applyMiddleware(thunk))
export default store
Mapping state and actions to props
const mapStateToProps = (state) => {
const { processState, isLogged} = state
return { processState, isLogged }
};
const mapDispatchToProps = (dispatch) => {
return {
//loadFinished: () => dispatch({ type: 'LOAD_FINISHED' })
startProcess: bindActionCreators(start, dispatch),
endProcess: bindActionCreators(stop, dispatch),
}
};
export default connect(mapStateToProps, mapDispatchToProps)(ReportStickerStatus);
When I dispatch startProcess my app got redirected to a empty page
THERES NO ANY ERRORS ON CONSOLE
UPDATE [ SOLVED ]
I had to return the state in each action, even in default
import initialState from './initialState'
const isLogged = (state = initialState, action) => {
switch (action.type) {
case 'SIGN_IN':
return {
...state,
value: 2
};
case 'LOAD_FINISHED':
return {
...state,
value: 1
};
case 'SIGN_OUT':
return {
...state,
value: -1
};
case 'FIRST_LOGIN':
return {
...state,
value: 3
};
case 'FB_LOGIN':
return {
...state,
value: 4
};
default:
return {
...state
};
}
}
export default isLogged
I am unable to dispatch an action to reducer.
State comes out just fine. Not sure where I have gone wrong.
For other user reducer, dispatch works just fine. my project has nested drawer navigation > tabs navigation > stack navigation and current page is the 3rd stack screen. Not sure if that is the issue or what.
Store.js
import { combineReducers, createStore } from '#reduxjs/toolkit';
import cartReducer from './cartSlice';
import userReducer from './userSlice';
const rootReducer = combineReducers({
userReducer: userReducer,
cartReducer: cartReducer,
})
const configureStore = () => createStore(rootReducer)
export default configureStore
cartSlice.js
const initialState = {
cart: [{ key: 1, data: { freq: 'Daily', duration: 30 } }]
}
const cartReducer = (state = initialState, action) => {
switch (action.types) {
case "ADD_TO_CART":
console.log(action)
return {
...state,
cart: [...state.cart, { key: 2, data: action.data }]
}
case "REMOVE_FROM_CART":
const idx = state.cart.map((cartItem) => (
cartItem.key === action.id
))
const tempNewCart = [...state.cart]
if (idx >= 0) {
tempNewCart.splice(idx, 1)
}
return { ...state, cart: tempNewCart }
case "CLEAR_CART":
return {
...state,
cart: []
}
default:
return state
}
}
export default cartReducer
SubscriptionQuantity Component
const mapStateToProps = (state) => {
console.log(state)
return {
cart: state.cartReducer.cart
}
}
const mapDispatchToProps = (dispatch) => {
// console.log(dispatch)
return {
addtoCartStore: (freq, duration) => dispatch({
type: 'ADD_TO_CART',
data: {
freq: freq,
duration: duration
}
})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SubscriptionQuantity)
function call for dispatch
const addtoCart = () => {
addtoCartStore('Alternate', 30)
navigation.navigate("CartScreen")
}
The issue was with the switch statement!!!!
it should be switch(action.type) not action.types. that's why it was going in on the default route. changed the typo and works fine now.!
This is the filterAction action that emits a value to to the persisted reducer. This action is called with dispatch() in a dropdown in a component.
import { SORT_BY_TITLE, SORT_BY_RELEASED_AT } from './types';
// sort by title
export const sortByTitle = () => ({
type: SORT_BY_TITLE
});
// sort by released at
export const sortByReleasedAt = () => ({
type: SORT_BY_RELEASED_AT
});
The corresponding filterReducer
import { SORT_BY_TITLE, SORT_BY_RELEASED_AT } from '../actions/types';
const initialState = {
sortBy: 'title'
};
export default function(state = initialState, action) {
switch(action.type) {
case SORT_BY_TITLE:
return {
...state,
sortBy: 'title'
};
case SORT_BY_RELEASED_AT:
return {
...state,
sortBy: 'releasedAt'
};
default:
return state;
}
};
The filterReducer value is the one persisted in the main combined reducer.
export default combineReducers({
books: booksReducer,
book: bookReducer,
form: addBookFormReducer,
filter: filterReducer
});
The app's store
import { createStore, applyMiddleware } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
const middleware = [thunk];
const persistConfig = {
key: 'root',
storage,
whitelist: ['filter']
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
export const store = createStore(persistedReducer, {}, applyMiddleware(...middleware));
export const persistor = persistStore(store);
The value persisted on the filter part of the main reducer gets displayed in the dropdown changes on which call the filterAction with dispatch().
Here's the booksReducer that creates the books part of the app's store so books are displayed in a component.
import {
GET_BOOKS,
BOOKS_LOADING,
DELETE_BOOK,
SORT_BY_TITLE,
SORT_BY_RELEASED_AT
} from '../actions/types';
const initialState = {
books: [],
loading: false
};
const booksReducer = (state = initialState, action) => {
switch(action.type) {
case BOOKS_LOADING:
return {
...state,
loading: true
};
case GET_BOOKS:
return {
...state,
books: action.payload,
loading: false
};
case DELETE_BOOK:
return {
books: [...state.books.filter(book => book._id !== action.payload.id)]
};
case SORT_BY_TITLE:
return {
...state,
books: [...state.books.sort((a, b) => a.title < b.title ? -1 : 1 )]
};
case SORT_BY_RELEASED_AT:
return {
...state,
books: [...state.books.sort((a, b) => a.releasedAt < b.releasedAt ? -1 : 1 )]
};
default:
return state;
}
};
export default booksReducer;
The filter part of the main reducer persists Ok on the page reload however the books list is displayed with the default by title sort.
How do I get the app to persist the sort on the page reload? The complete repo is on https://github.com/ElAnonimo/booklister
On the BookList load the getBooks() action return reset the sorted books list to its default sorting so it was easier to persist only the filter prop of the store then sort the books list on each load of the BookList component.
The changes were made
to booksReducer
import {
GET_BOOKS,
BOOKS_LOADING,
DELETE_BOOK
} from '../actions/types';
const initialState = {
books: [],
loading: false
};
const booksReducer = (state = initialState, action) => {
switch(action.type) {
case BOOKS_LOADING:
return {
...state,
loading: true
};
case GET_BOOKS:
return {
...state,
books: action.payload,
loading: false
};
case DELETE_BOOK:
return {
books: [...state.books.filter(book => book._id !== action.payload.id)]
};
default:
return state;
}
};
export default booksReducer;
to BookList
class BookList extends Component {
componentDidMount() {
this.props.getBooks();
}
applySorting(books) {
const sortBy = this.props.filter.sortBy;
if (!sortBy) {
return books;
}
return books.sort((a, b) => a[sortBy] < b[sortBy] ? -1 : 1);
}
render() {
const { books, loading } = this.props.books;
let booksContent;
if (!books || loading) {
booksContent = <Spinner />;
} else {
if (books.length > 0) {
booksContent = this.applySorting(books).map(book => <BookItem book={book} key={book._id} />);
} else {
booksContent = <h4>No books found</h4>;
}
}
...
...