How do I reset the state to its initial state? - javascript

I can't seem to reset the default state; how do I do that? I tried this but all it does is add state to state and calls it undefined.
const initialState = {
name: null,
coins: 0,
image: null,
};
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case types.ADD_GROUP_COINS:
return {
...state,
coins: state.coins + action.coins
};
case types.DELETE_GROUP:
return {
state: undefined
};
default:
return state;
}
}

To reset the state to the initialState, simply return initialState, like this:
case types.DELETE_GROUP:
return initialState;
Remember that in the reducer, the object that you return is the new state. You don't need to wrap it in another object, like this:
return {
state: ...
}
That will give you a property called state in your state, which isn't at all what you need.
From the documentation:
The reducer is a pure function that takes the previous state and an action, and returns the next state.
It's easy to get confused about this, so be careful! Take a look at your default case if you're still not quite sure: you're returning the old state variable as the new state, not { state: state } which you are essentially doing with the current DELETE_GROUP handler.

Related

Redux | Why this store's parameter type changes after second click?

I'm trying to push a new value in the store's state. It works fine the first time I click on the button "Add item", but the second time I got the following error: "state.basket.push is not a function". I configure the action to console log the state and got the following results:
1st click: {...}{basketItems: Array [ "44" ]}
2nd click: Object {basketItems: 0 }
Why the variable type is changing from array to an int?
Here is the code for the rendered component:
function Counter({ basketItems,additem }) {
return (
<div>
<button onClick={additem}>Add item</button>
</div>
);
}
const mapStateToProps = state => ({
basketItems: state.counterReducer.basketItems,
});
const mapDispatchToProps = dispatch => {
return {
additem: ()=>dispatch({type: actionType.ADDITEM, itemName:'Dummy text' }),
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Counter);
And the reducer looks like this:
import {ADDITEM} from "../actions/types";
const initialState = { basket: [], };
export default function reducer(state = initialState, action) {
switch (action.type) {
case ADDITEM:
console.log(state);
// let newBasket = state.basket.push('44');
return {
...state,
basket: state.basket.push('44')
};
default:
return state;
}
}
I'm copying the state before updating the basket to prevent weird behaviors.
There's two problems here:
state.basket.push() mutates the existing state.basket array, which is not allowed in Redux
It also returns the new size of the array, not an actual array
So, you're not doing a correct immutable update, and you're returning a value that is not an array.
A correct immutable update here would look like:
return {
...state,
basket: state.basket.concat("44")
}
Having said that, you should really be using our official Redux Toolkit package, which will let you drastically simplify your reducer logic and catch mistakes like this.

Reducer not returning updated state

I can't get my reducer to return updated state.
The action (confirmed with debugger) is an array of objects - something like: [{name: "test"}, {name: "second_test"}]
I think something must be wrong with my spread operator, although I've also tried Object.assign() in the debugger and that seems to return the expected result.
My components is apparently just getting the default state. Here's my reducer code. Any help would be appreciated. Thank you!
const initialState = {
current: {},
all: []
}
export default function deckReducer(state = initialState, action) {
switch(action.type) {
case 'CREATE_DECK':
return {...state, all: [...state.all, action.payload]}
case 'FETCH_DECKS':
debugger;
return {...state, all: action.payload}
default: return state
}
}
I had this very issue recently (exactly as you describe), and I resolved the problem by using the immutability-helper package which is listed here on the ReactJS docs.
This approach allows you to delegate the heavy lifting of state immutability and nested state updates. You should find this resolves your issue:
import update from 'immutability-helper';
const initialState = {
current: {},
all: []
}
export default function deckReducer(state = initialState, action) {
switch(action.type) {
case 'CREATE_DECK': {
/* Add payload to nested state.all list */
return update(state, { all : { $push : [action.payload] }});
}
case 'FETCH_DECKS': {
/* Replace state.all with incoming payload */
return update(state, { all : { $set : action.payload }});
}
default: return state
}
}

How can I mutate multiple state items in redux-react store

I have multiple values stored in my redux initial state, and I have one action handler StepOneFn that is taking in all the values my component has given it to change. I want to update the initial state to change only some of the values. I'm not sure how to go about doing it.
let initial_state = {
house_name:"",
address:"",
city:"",
state:"",
zip:0,
img:"",
mortgage:0,
rent:0
}
const step_one = "step_one"
export default function reducer(state = initial_state,action){
switch(action.type){
default:
return state;
case step_one:
return {...state,...action.payload}
}
}
export function StepOneFn(name,address,city,state,zip){
return{
type:step_one,
payload:{
name,
address,
city,
state,
zip
}
}
}
If you want to change only some values you can do like this
case step_one:
return {...state, address:action.payload.address, city:action.payload.city}
}
Now it only changes city and address as per payload others are unchanged.

How to change nested Object without mutating it in Redux

I am pretty new guy to redux.I am little bit confused that how to change this data without mutating it.
my data structure like this
{
postOwnwerName:"",
postTags:[],
photos:[
{
id:dc5c5d7c5s,
caption:null
},
{
id:dccccccc5s,
caption:null
}
],
}
Whent this function fires
this.props.updateCaption(id,caption)
my Reducer should set data according to the id in the data structure without mutating it
import * as types from '../Actions/actionTypes';
const initialState = {
postOwnwerName:"",
postTags:[],
photos:[],
};
export default function uploadReducer(state=initialState,action) {
switch (action.type){
case types.SETPHOTOSTATE:
return Object.assign({},state,{ photos:state.photos.concat(action.payload) });
case types.SETCAPTIONTEXT:
//this method is not working
return (
Object.assign({},state,state.photos.map((data) => {
if(data.id == action.payload.id){
return Object.assign({},data,{caption:action.payload.caption})
}else{
return data
}
}))
)
default:
return state
}
}
if the state object has many level it will be difficult to change state without mutating. In those scenario I first copy the state deeply and then make changes to the new state and return new state. See here Cloning object deeply. You can try this once.
export default function uploadReducer(state=initialState,action) {
let newState = JSON.parse(JSON.stringify(state));
switch (action.type){
case types.SETPHOTOSTATE:
newState.photos.push(action.payload);
return newState;
case types.SETCAPTIONTEXT:
newState.photos.map((data) => {
if(data.id == action.payload.id){
data.caption = action.payload.caption;
}
});
return newState;
default:
return newState;
}
}

dispatch action triggering, but redux store not updating

Currently in my React-Redux app, I would like to use React to set the state of show to either false, or true. When set to true, the app will initialize. (There are multiple components, so it would make sense to do this using react/redux.)
However, my current issue is that even though I have connected my app using react redux, and my store using provider, the dispatch action will be called, without updating the store(I am using redux dev tools to double check, as well as in app testing).
I have attached the code I feel is relevant, however, the entire code base is available as a branch specifically made for this question here. I have spent quite sometime on this(actually an understatement) and any contributions would be greatly appreciated.
Component Relevant Code
hideBlock(){
const{dispatch} = this.props;
dispatch(hideBlock);
}
return(
<div className = "works">
<button id="show-block" type="button" className="show-hide-button" onClick={this.showBlock}>show</button>
<button id="hide-block" type="button" className="show-hide-button" onClick={this.hideBlock}>Hide</button>
</div>
);
function mapStateToProps(state) {
const {environment} = state;
return{
environment
}
}
export default connect(mapStateToProps)(Form);
Action
import * as types from "../constants/ActionTypes";
export function showBlock(show) {
return {
type: types.SHOW,
show: true
};
}
export function hideBlock(hide) {
return {
type: types.HIDE,
show: false
};
}
Reducer
import * as types from "../constants/ActionTypes";
const initialState = {
show: false
};
export default function environment(state = initialState, action) {
switch(action.type) {
case types.HIDE:
return Object.assign({}, state, {
type: types.HIDE
});
case types.SHOW:
return Object.assign({}, state, {
type: types.SHOW
});
default:
return state;
}
}
Thank you, and once again any help is very much so appreciated.
So, I asked a co-worker for help and it turns out that I was returning my action as an object instead of a function. So, for instance, changing the following code:
hideBlock(){
const{dispatch} = this.props;
dispatch(hideBlock);
}
to
hideBlock(){
const{dispatch} = this.props;
//change hideBlock to hideBlock()
dispatch(hideBlock());
}
solved the issue. Thanks Andrew!
It looks like state.show is set in initialState but never modified in any of the cases inside the reducer. The action has show: true, but the reducer never uses this to update the state.
Here's a simplified reducer that updates state.show based on the action's show field:
export default function environment(state = initialState, action) {
switch(action.type) {
case types.HIDE:
case types.SHOW:
return Object.assign({}, state, {
show: action.show
});
default:
return state;
}
}
Alternatively, because action.show and action.type have the same data, you could remove show from the actions and rely on the action type:
export default function environment(state = initialState, action) {
switch(action.type) {
case types.HIDE:
return Object.assign({}, state, {
show: false
});
case types.SHOW:
return Object.assign({}, state, {
show: true
});
default:
return state;
}
}

Categories

Resources