I am using redux wth reactjs.
I want to store simple key/value pairs but can't get the reducer syntax right.
In this case each key/value pair will hold a connection to an external system.
Is this the right way to do it? I'm at the beginning with redux so it's a bit of mystery.
export default (state = {}, action) => {
switch(action.type) {
case 'addConnection':
return {
connections: {
...state.connections, {
action.compositeKey: action.connection
}
}
default:
return state
}
}
This worked for me:
export default (state = {}, action) => {
switch(action.type) {
case 'addConnection':
return {
...state,
connections: {
...state.connections,
[action.compositeKey]: action.connection
}
}
default:
return state
}
}
From the docs:
https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#correct-approach-copying-all-levels-of-nested-data
You just have a couple mistakes with {} instead of [] and forgetting to use Object.assign.
const reducer = (state = {}, action) => {
switch (action.type) {
case 'addConnection':
return Object.assign({}, state, {
connections: [
...state.connections,
{
[actions.compositeKey]: action.connection
}
]
});
default:
return state;
}
}
export default reducer;
It might help to see it expressed this way too. It does the same thing but I think it reads a little nicer
const reducer = (state = {}, {type, compositeKey, connection}) => {
switch (type) {
case 'addConnection':
return Object.assign({}, state, {
connections: state.connections.concat({
[compositeKey]: connection
})
});
default:
return state;
}
}
export default reducer;
Or if you're using Immutable, something like this
import Immutable from 'immutable';
const reducer = (state = Immutable.Map(), {type, compositeKey, connection}) => {
switch (type) {
case 'addConnection':
return state.set(
'connections',
state.get('connections').concat({
[compositeKey]: connection
})
);
default:
return state;
}
}
export default reducer;
This may work
const reducer = (state = {}, {type, compositeKey, connection}) => {
switch (type) {
case 'addConnection':
var newData={};
newData[compositeKey]=connection;
return Object.assign({}, state, newData)
});
default:
return state;
}
}
export default reducer;
Related
Is it correct if we use CONSTANT which was imported and added inside of this reducer?
import { SOME_CONST } from './SOME_CONST'
export const reducer = (state = {}, action) {
switch (action.type) {
case types.SOME_TYPE:
return {
...state,
key: SOME_CONST,
}
default:
return state
}
}
It's correct. See the official shopping-cart example. They import the action type constants and use them in reducers. A key principle is that the reducer must be kept pure and idempotent.
import {
ADD_TO_CART,
CHECKOUT_REQUEST,
CHECKOUT_FAILURE
} from '../constants/ActionTypes'
const initialState = {
addedIds: [],
quantityById: {}
}
const addedIds = (state = initialState.addedIds, action) => {
switch (action.type) {
case ADD_TO_CART:
if (state.indexOf(action.productId) !== -1) {
return state
}
return [ ...state, action.productId ]
default:
return state
}
}
// ...
I build an app in React with Redux and I try to send to my state an object and I try to save it in 'thisUser' but I don't know how to write that 'return' because mine doesn't work.
My Redux state:
const initialState = {
thisUser: {}
}
export function usersReducer(state = initialState, action) {
switch (action.type) {
case 'users/addUser':
return { ...state, thisUser: { ...state.thisUser, ...action.payload} } //the problem
default:
return state
}
}
Dispatch method:
dispatch({ type: "users/addUser", payload: new_user });
Can you tell me how to write that return, please?
If you want to append new user then why are you using object type. You should use Array Type thisUser.
const initialState = {
thisUser: []
}
export function usersReducer(state = initialState, action) {
switch (action.type) {
case 'users/addUser':
return { ...state, thisUser: [ ...state.thisUser,action.payload ] }
default:
return state
}
}
Or
If you want to save only single user object then change only that line in your code:
return { ...state, thisUser: action.payload }
It's better to use an array type for if you have a list of users .
If you have a case when you need to use an object just change the brackets [ ] on my code to curly braces { } .
const initialState = {
thisUser: [],
}
export function usersReducer(state = initialState, action) {
switch (action.type) {
case 'users/addUser':
return { ...state, thisUser: [ ...state.thisUser, ...action.payload]}
default:
return state
}
}
I am working on a React application and I am using Redux to store the state. I have the following code:
menu.reducer.js:
import { GET_MENU } from './menu.types';
const INITIAL_STATE = []
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case GET_MENU:
return [ ...action.payload ];
default:
return state;
}
}
menu.actions.js:
import { apiUrl, apiConfig } from '../../util/api';
import { GET_MENU } from './menu.types';
export const getMenu = () => async dispatch => {
const response = await fetch(`${apiUrl}/menu`);
if (response.ok) {
const menuData = await response.json();
dispatch({ type: GET_MENU, payload: menuData })
}
}
In the above Reducer, the initial state is an empty array. Dispatching the GET_MENU action, changes the initial state so that it contains an array of menu items instead.
The array that is fetched in the GET_MENU action is of the following:
However I want my initial state to be like the following:
const INITIAL_STATE = {
menuArray = [],
isSending = false
}
In the GET_MENU case in the reducer code, I am not sure what the correct syntax is to use in order to assign the menuArray property in the state to the array that is returned from the GET_MENU action.
Any insights are appreciated.
The state is simply a JavaScript value. If you want it to be an object with two properties, this isn't the right syntax:
const INITIAL_STATE = {
menuArray = [],
isSending = false
}
This is:
const INITIAL_STATE = {
menuArray: [],
isSending: false
}
Your reducer will now need to also return objects. You'll want to return a new object each time. Here's how you can do your reducer, specifically:
import { GET_MENU } from './menu.types';
const INITIAL_STATE = {
menuArray: [],
isSending: false
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case GET_MENU:
return { ...state, menuArray: [...action.payload] };
default:
return state;
}
}
This says "create an object comprised of all the properties of the previous state but with the menuArray property set to the payload."
import { GET_MENU } from './menu.types';
const initialState= {
menuArray: [],
isSending: false
}
export default (state = initialState, action) => {
switch (action.type) {
case GET_MENU:
return {...state, menuArray: action.payload};
default:
return state;
}
}
import { GET_MENU } from './menu.types';
const INITIAL_STATE = {
menuArray: [],
isSending: false
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case GET_MENU:
return {
...state,
menuArray: action.payload
};
default:
return state;
}
}
Is this reducer OK:
function someReducer(state = initialState, action) {
if (action.type === SOME_ACTION) {
const newState = Object.assign( {}, state );
// ...
// doing whatever I want with newState
// ...
return newState;
}
return state;
}
and if is OK, why we need all those immutable libraries to complicate our lives.
p.s
Just trying to comprehend Redux and immutability
export default function (state = initialState, action) {
const actions = {
SOME_ACTION: () => {
return {
...state
}
},
ANOTHER_ACTION: () => {
return {
...state
error: action.error
}
},
DEFAULT: () => state;
}
return actions[action.type] ? actions[action.type]() : actions.DEFAULT();
}
I prefer doing this instead. I am not a big fan of switch statements.
The standard approach is to use a switch/case with spread syntax (...) in your reducer.
export default function (state = initialState, action) {
switch (action.type) {
case constants.SOME_ACTION:
return {
...state,
newProperty: action.newProperty
};
case constants.ERROR_ACTION:
return {
...state,
error: action.error
};
case constants.MORE_DEEP_ACTION:
return {
...state,
users: {
...state.users,
user1: action.users.user1
}
};
default:
return {
...state
}
}
}
You can then use ES6 spread syntax to return your old state with whatever new properties you want changed/added to it.
You can read more about this approach here...
https://redux.js.org/recipes/using-object-spread-operator
I found something that I really like:
import createReducer from 'redux-starter-kit';
const someReducer = createReducer( initialState, {
SOME_ACTION: (state) => { /* doing whatever I want with this local State */ },
SOME_ANOTHER_ACTION: (state) => { /* doing whatever I want with local State */ },
THIRD_ACTION: (state, action) => { ... },
});
If your state has nested objects or arrays, Object.assign or ... will copy references to your older state variable and it may cause some issue. This is the reason why some developers use immutable libraries as in most of the case state has deep nested array or objects.
function someReducer(state = initialState, action) {
if (action.type === SOME_ACTION) {
const newState = Object.assign( {}, state );
// newState can still have references to your older state values if they are array or orobjects
return newState;
}
return state;
}
So, I'm trying to use some piece of state from one reducer in another reducer, and I looked for a solution and seems the package reduce-reducers does exactly that, buth here's my question ...
I have the following rootReducer.js file where I import all my reducers and combine them with combineReducers like this ...
import { combineReducers } from "redux";
import globalReducer from "./globalReducer";
import booksReducer from "../features/books/booksReducer";
import categriesReducer from "../features/categories/categoriesReducer";
import authorsReducer from "../features/authors/authorsReducer";
const rootReducer = combineReducers({
global: globalReducer,
books: booksReducer,
categories: categriesReducer,
authors: authorsReducer
});
export default rootReducer;
Now I want to use some state from the authors reducer in the books reducer, how can I achieve that with reduce-reducers package?
reduce-reducers works like "merge" of reducers:
const reducer = (state = 0, action) => {
switch (action.type) {
case 'ADD':
return state + action.value;
case 'MULTIPLE':
return state * action.value;
default:
return state;
}
};
The same can be written with reduce-reducers:
const addReducer = (state = 0, action) => {
switch (action.type) {
case 'ADD':
return state + action.value;
default:
return state;
}
};
const multipleReducer = (state = 0, action) => {
switch (action.type) {
case 'MULTIPLE':
return state * action.value;
default:
return state;
}
};
const reducer = reduceReducers(addReducer, multipleReducer, 0);
So on your task, it means, that you should rewrite your authorsReducer and booksReducer so it gets entire state as first argument, not only its own authors part:
const before = (state = [], action) => {
switch (action.type) {
case `NEW_BOOK`:
return state.concat([action.book]);
default:
return state;
}
}
const now = (state = {}, action) => {
switch (action.type) {
case `NEW_BOOK`:
return {
...state,
books: state.books.concat([action.book]),
};
default:
return state;
}
}
BUT! I think this is not what you're actually want.
There is another package that does exactly what you need combine-section-reducers
It allows you to access root state from any other reducer:
const before = (state = [], action) => {
switch (action.type) {
case `NEW_BOOK`:
return state.concat([action.book]);
default:
return state;
}
}
const now = (state = [], action, rootState) => {
switch (action.type) {
case `NEW_BOOK`:
return state.concat([{
...action.book,
author: rootState.authors[action.book.authorId],
}]);
default:
return state;
}
}