I am trying to use stackoverflow api to make my first react redux project. I need to maintain a state like the following:
{
selectedTag: reactjs,
selectedSortOrder: activity,
items:[]
}
My reducer is given below:
const initialState = {
selectedTag: 'C#',
selectedSortOrder: 'activity', items: []
}
function SelectTag(state = initialState, action) {
switch (action.type) {
case SELECTTAG:
// console.log(state);
return Object.assign({}, state, { selectedTag: action.selectedTag });
default:
return state;
}
}
function SelectSortOrder(state = initialState, action) {
switch (action.type) {
case SELECTSORTORDER:
//console.log(state);
return Object.assign({}, state, { selectedSortOrder: action.selectedSortOrder });
default:
return state;
}
}
function ReceivePosts(state = { items: [] }, action) {
switch
(action.type) {
case RECEIVESORTEDPOSTS:
case RECEIVEPOST:
console.log(state);
return Object.assign({}, state, { items: action.items })
default:
return state
}
}
const rootReducer = combineReducers({ ReceivePosts, SelectTag, SelectSortOrder })
And mapStateToProps is:
const mapStateToProps = (state) => {
const selectedTag = state.SelectTag.selectedTag;
const items = (state.ReceivePosts.items);
const tags = (state.ReceiveTags.tags);
const selectedSortOrder = state.SelectSortOrder.selectedSortOrder;
return {selectedTag, items, tags, selectedSortOrder};
}
I have 2 problems here:
a. State does not remember all the data. For eg. suppose I select the tag first and then get items, my state has only items. SelectedTag is not set in the state.
b. I am not sure why mapStateToProps needs the reducer name. Eg: const selectedTag = state.SelectTag.selectedTag;
Actually it should be state.selectedTag. But my code expects the reducer name "SelectTag" to fetch the state value.
What am I doing wrong?
You haven't configured your reducers correctly. The initialState is assigned to all of your reducers which isn't required
const initialState={
selectedTag:'C#',
selectedSortOrder:'activity',
items:[]
}
function SelectTag(state = initialState.selectedTag, action){
switch(action.type){
case SELECTTAG:
return action.selectedTag
default:
return state;
}
}
function SelectSortOrder(state = initialState.selectedSortOrder, action){
switch(action.type){
case SELECTSORTORDER:
return action.selectedSortOrder
default:
return state;
}
}
function ReceivePosts(state = {items:[]}, action){
switch(action.type){
case RECEIVESORTEDPOSTS:
case RECEIVEPOST:
console.log(state);
return Object.assign({}, state, {items:action.items})
default:
return state
}
}
const rootReducer = combineReducers({ReceivePosts, SelectTag, SelectSortOrder})
And in mapStateToProps you would use it like
const mapStateToProps = (state) => {
const selectedTag = state.SelectTag;
const items = (state.ReceivePosts.items);
const tags = (state.ReceiveTags.tags);
const selectedSortOrder = state.SelectSortOrder;
return {selectedTag, items, tags, selectedSortOrder};
}
1. Try this code change
const initialState = {
selectedTag: 'C#',
selectedSortOrder: 'activity',
items: []
}
function SelectTag(state = initialState.selectedTag, action) {
switch (action.type) {
case SELECT TAG:
return {
...state,
selectedTag: action.selectedTag
}
default:
return state;
}
}
function SelectSortOrder(state = initialState.selectedSortOrder, action) {
switch (action.type) {
case SELECTSORTORDER:
return {
...state,
selectedSortOrder: action.selectedSortOrder
}
default:
return state;
}
}
function ReceivePosts(state = { items: [] }, action) {
switch (action.type) {
case RECEIVESORTEDPOSTS:
case RECEIVEPOST:
return {
...state,
items: action.items
}
default:
return state
}
}
const rootReducer = combineReducers({ ReceivePosts, SelectTag, SelectSortOrder });
2. I am not sure why mapStateToProps needs the reducer name. Eg: const selectedTag = state.SelectTag.selectedTag;
Its because when you use combinereducers, you are combining multiple slices of data, then you need to specify the slice from which you want to fetch the data.
const rootReducer = combineReducers({
receivePosts = ReceivePosts,
selectTag = SelectTag,
selectSortOrder = SelectSortOrder
});
Issue: You have not configured your initialstate properly, you are using the same initialstate in SelectTag and also in SelectSortOrder, if the initial state is same then why do you need two reducers?
Related
I have children list (reducer) and families list (reducer). The families list contains array of children.
How to update the child in the family's array of children when update a child from the children list using Redux?
This is my children reducer update case:
export function children(state = [], action) {
// ...
case types.UPDATE_CHILD: {
const childIndex = state.findIndex(child => child.id === action.id);
state[childIndex] = action.updatedChild;
return state;
}
// ...
}
When redux action fired, by default it goes through all of the reducers.
In general reducer architecture, we use something like { switch } syntax, and if the reducer don't have a responded { case } to the action, the action will go through { default } option in reducer.
const actionA = payload => (dispatch, getState) => dispatch({ type: 'a', payload })
const reducerA = (state = {}, action) => {
switch (action.type) {
case 'a':
// action will be reduced here
return action.payload
default:
return state;
}
}
const reducerB = (state = {}, action) => {
switch (action.type) {
case 'b':
return action.payload
default:
// action will be reduced here
return state;
}
}
Therefore, just add { types.UPDATE_CHILD } case at family reducer.
const reducerB = (state = {}, action) => {
switch (action.type) {
case 'b':
return action.payload
case 'a':
// now action will be reduced here
return action.payload
default:
return state;
}
}
Another thing about your reducer, that is you manipulate state directly at the reducer and not at the return, change it to -
case types.UPDATE_CHILD: {
return state.filter(child => child.id === action.id ? action.updatedChild : child);
}
populate my initialState with json api call from a component or from here
const initialState = {
myvalues: [] ---->here i want to populate this array
};
const reducer = (state = initialState, action) => {
const newState = { ...state };
switch (action.type) {
case "Update":
console.log(newState);
// newState.myvalues = action.key.title.value;
default:
return newState;
}
};
export default reducer;
To populate your initialState with data from an API, you can create e.g. an FETCH_INIT_DATA_ACTION, which get's dispatched right after you initialised your store.
// ...
const store = createStore(/* ... */)
store.dispatch({ type: 'FETCH_INIT_DATA_ACTION' })
// ...
whereas FETCH_INIT_DATA_ACTION triggers a redux-thunk, saga, effect or whatever you want to use.
You can do it like this:
const reducer = (state = initialState, action) => {
switch (action.type) {
case "Update":
return { ...state, myvalues: action.payload }
default:
return state;
}
};
And when you dispatch it you should put your API data in payload.
I'm trying to find what would be the best pattern to manage my reducers.
I have the following page:
I know I could've used redux-forms for this, but this is not the point since I only used these fields/form as an example.
We have multiple ways of handling this on redux:
1: having a single action to update those fields values based on the input's name property:
const UPDATE_VALUES = 'UPDATE_VALUES';
const INITIAL_STATE = {
aString: '',
setOfValues1: [],
setOfValues2: []
};
const reducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case UPDATE_VALUES: {
if (action.name === 'setOfValues1' || action.name === 'setOfValues2') {
const array = [...state[action.name]];
array.push(action.value);
return {
...state,
[action.name]: array
};
}
return {
...state,
[action.name]: action.value
};
}
default:
return state;
}
};
2: having multiple actions to each field value:
const UPDATE_A_STRING = 'UPDATE_A_STRING';
const UPDATE_SET_1 = 'UPDATE_SET_1';
const UPDATE_SET_2 = 'UPDATE_SET_2';
const INITIAL_STATE = {
aString: '',
setOfValues1: [],
setOfValues2: []
};
const reducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case UPDATE_A_STRING:
return {
...state,
aString: action.value
};
case UPDATE_SET_1: {
const array = [...state.setOfValues1];
array.push(action.value);
return {
...state,
setOfValues1: array
};
}
case UPDATE_SET_2: {
const array = [...state.setOfValues2];
array.push(action.value);
return {
...state,
setOfValues2: array
};
}
default:
return state;
}
};
and more ways that I'm not aware of.
what would be the good practice/best pattern in this case? Where can I look for, to learn more patterns to situations like these and other situations as well?
What about this?
const UPDATE_VALUES = 'UPDATE_VALUES';
const INITIAL_STATE = {
aString: '',
setOfValues1: [],
setOfValues2: []
};
const setOfValues = ['setOfValues1', 'setOfValues2'];
const reducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case UPDATE_VALUES: {
if (setOfValues.includes(action.name)) {
return {
...state,
[action.name]: state[action.name].concat(action.value);
};
}
return {
...state,
[action.name]: action.value
};
}
default:
return state;
}
};
I have a reducer that looks like this:
const chart = combineReducers({
data,
fetchProgress,
fetchError,
updateProgress,
updateError,
});
I now would like to not only a chart but multiple charts.
const charts = (state = {}, action = {}) => {
if (action.type == FETCH_CHART || action.type == ...) {
let newChart = chart(state[action.id], action);
return Object.assign({}, state, {[action.id]: newChart});
}
return state;
}
Is there something conceptually wrong to do this?
If no, is there a better way to achieve the same result?
There is nothing wrong with the concept. In fact, I'd say this is my preferred approach when needing to store similar data in the redux store
To improve it, you could wrap it in a higher-order reducer to handle the id part of it. Something like:
const handleIds = (reducer) => (state = {}, action) => {
if (action.id) {
let idState = state[action.id]
let newState = reducer(idState, action)
if (newState !== idState) {
return { ...state, [action.id]: newState }
}
}
return state
}
This will pass on any action with an id and merge the resulting state into it's state with that id as it's key, if the state has changed.
Then your reducer becomes:
const singleChart = (state = {}, action = {}) => {
if (action.type == FETCH_CHART || action.type == ...) {
let newChart = chart(state, action);
return newChart;
}
return state;
}
const charts = handleIds(singleChart)
Then combine it into your store:
const chart = combineReducers({
data,
fetchProgress,
fetchError,
updateProgress,
updateError,
charts
});
Personally I would breakdown the logic to further sub reducers in order to have a better separation of concerns. In case you will add multiple charts and in case you will need to add more logic/settings/data to your actions, you will end up to modify too much your single reducer.
I follow with a small example where you could have 3 charts.
// bubbleChartReducer.js
export function bubble (state = {}, action) {
switch (action.type) {
case 'FETCH_BUBBLE_CHART':
return {
[action.id]: new chart(action.id, action)
}
default:
return state
}
}
// pieChartReducer.js
export function pie (state = {}, action) {
switch (action.type) {
case 'FETCH_PIE_CHART':
return {
[action.id]: new chart(action.id, action)
}
default:
return state
}
}
// linearChartReducer.js
export function pie (state = {}, action) {
switch (action.type) {
case 'FETCH_LINEAR_CHART':
return {
[action.id]: new chart(action.id, action)
}
default:
return state
}
}
// chartsReducer.js
import { bubble } from 'bubbleChartReducer'
import { pie } from 'pieChartReducer'
import { linear } from 'linearChartReducer'
import { combineReducers } from 'redux'
export combineReducers({
bubble,
pie,
linear
})
I know how to do with push method:
import * as types from '../constants/ActionTypes'
const initialState = {
designBox: [],
}
import * as types from '../constants/ActionTypes'
const initialState = {
designBox: [],
}
export default function(state = initialState, action) {
switch (action.type) {
case types.CREATE_DESIGN_BOX:
let newState = Object.assign({}, state);
newState.designBox.push(action.payload)
return newState
default:
return state
}
}
But I don't know how to do with ... method
Now my code has problem, The designBox can't add objects,
it only has one item, because it just overwritten by new action.payload
import * as types from '../constants/ActionTypes'
const initialState = {
designBox: [],
}
export default function(state = initialState, action) {
switch (action.type) {
// action.payload format -> { width:200,height:300,text:'abc'}
case types.CREATE_BOX:
return {
...state,
designBox: [action.payload]
}
default:
return state
}
}
How can I do this with ... method ??
Spread the the array as well:
return {
...state,
designBox: [...state.designBox, action.payload]
}
Also, your state doesn't need to be an object. If it only contains an array just make it an array:
const initialState = [];
Use array destructor
case types.CREATE_BOX:
return {
...state,
designBox: [...state.designBox,action.payload]
}
There's no way using object spread to manipulate keys, only replace them entirely. You can however refer to the original object when you're overriding keys:
return {
...state,
designBox: state.designBox.concat(action.payload)
}