Why In redux Output is coming like this --> State Changed{} - redux

I am learning redux with simple age Increment and Decrement example here is the code
const { createStore } = require(`redux`);
const initialState = {age: 21};
const reducerOne = (state = initialState, action) => {
const newState = {...state};
if(action.type === `ADD`) {
newState.age = action.value;
}
if(action.type === `SUBTRACT`) {
newState.age = action.value;
}
return newState;
}
const store = createStore(reducerOne);
store.subscribe(() => {
console.log(`State Changed` + JSON.stringify(store.getState()));
})
store.dispatch({type: `ADD`, val: 10});
store.dispatch({type: `SUBTRACT`, val: 5});
But in Output it is showing like this --> State Changed{}
Help how to fix this and to get Output

Your action is posting the val property and your reducer is reading the value property.
Change your actions this way and it will work:
store.dispatch({type: `ADD`, value: 10});
store.dispatch({type: `SUBTRACT`, value: 5});
EDIT:
You are replacing your old age value, but probably you want to add or subtract from it. You have to modify your reducer to achieve such behaviour:
const reducerOne = (state = initialState, action) => {
const newState = {...state};
if(action.type === `ADD`) {
// add to the previous `age` value and do not overwrite it
newState.age = state.age + action.value;
}
if(action.type === `SUBTRACT`) {
// subtract from the previous `age` value and do not overwrite it
newState.age = state.age - action.value;
}
return newState;
}

Related

I cannot understand WHY I cannot change state in Redux slice

I get the array of objects coming from backend, I get it with socket.io-client. Here we go!
//App.js
import Tickers from "./Components/TickersBoard";
import { actions as tickerActions } from "./slices/tickersSlice.js";
const socket = io.connect("http://localhost:4000");
function App() {
const dispatch = useDispatch();
useEffect(() => {
socket.on("connect", () => {
socket.emit("start");
socket.on("ticker", (quotes) => {
dispatch(tickerActions.setTickers(quotes));
});
});
}, [dispatch]);
After dispatching this array goes to Action called setTickers in the slice.
//slice.js
const tickersAdapter = createEntityAdapter();
const initialState = tickersAdapter.getInitialState();
const tickersSlice = createSlice({
name: "tickers",
initialState,
reducers: {
setTickers(state, { payload }) {
payload.forEach((ticker) => {
const tickerName = ticker.ticker;
const {
price,
exchange,
change,
change_percent,
dividend,
yeild,
last_trade_time,
} = ticker;
state.ids.push(tickerName);
const setStatus = () => {
if (ticker.yeild > state.entities[tickerName].yeild) {
return "rising";
} else if (ticker.yeild < state.entities[tickerName].yeild) {
return "falling";
} else return "noChange";
};
state.entities[tickerName] = {
status: setStatus(),
price,
exchange,
change,
change_percent,
dividend,
yeild,
last_trade_time,
};
return state;
});
return state;
},
},
});
But the state doesn't change. I tried to log state at the beginning, it's empty. After that I tried to log payload - it's ok, information is coming to action. I tried even to do so:
setTickers(state, { payload }) {
state = "debag";
console.log(state);
and I get such a stack of logs in console:
debug
debug
debug
3 debug
2 debug
and so on.

Why filter method in my reducer returns an array of proxy? -Redux Toolkit

so i want to delete an item from array, onClick but when i log the filtered data in the console i get an array of Proxy.
i tried Changing my code but nothing worked
whats wrong here in itemRemoved?
import { createSlice, createAction } from "#reduxjs/toolkit";
// Action Creater
const slice = createSlice({
name: "shoppingCart",
initialState: [],
reducers: {
itemAdded: some code // ,
itemRemoved: (cart, { payload }) => {
cart.filter((item) => {
if (item.id === payload.id) {
if (item.count === 1) {
return cart.filter((item) => item.id !== payload.id);
}
else {
const itemIndex = cart.indexOf(item);
cart[itemIndex].count = cart[itemIndex].count - 1;
return cart;
}
}
});
},
},
});
export const { itemAdded, itemRemoved } = slice.actions;
export default slice.reducer;
Assuming you want to remove the element with the id you are passing through the dispatch function
itemRemoved: (state, { payload }) => {
const newCart = state.cart.filter(item => item.id !== payload.id)
const state.cart = newCart
return state
}),

update value of an element of object array in redux store

There is a challenge update existing elements value in json array in redux store by an action creater.
You can run code here also shared it below;
console.clear()
const CreateTeam = (team, point) => {
return {
type:"CREATE_TEAM",
payload: {team, point}
}
}
const UpdateTeam = (team, point) => {
return {
type:"UPDATE_TEAM_POINT",
payload: {team, point}
}
}
const TeamReducer = (state = [], action) => {
if(action.type == "CREATE_TEAM")
{
return [...state, action.payload]
}
if(action.type == "UPDATE_TEAM_POINT")
{
let point=action.payload.point;
return [...state, {
...state.teams,
point:point
}]
}
return state;
}
const { createStore, combineReducers } = Redux;
const league = combineReducers({
teams: TeamReducer
})
const store = createStore(league);
store.dispatch(CreateTeam("TeamA",10));
store.dispatch(CreateTeam("TeamB",20));
store.dispatch(UpdateTeam("TeamA",15));//not work
console.log(store.getState())
create actions works fine, I expected the point value of TeamA set to 15.. but its added new object has only "point" property value 15
There is an error in name of actionTypes:
action dispatches type:"UPDATE_TEAM"
reducer handles action.type == "UPDATE_TEAM_POINT"
You have to perform immutable change, try this:
const TeamReducer = (state = [], action) => {
if(action.type == "CREATE_TEAM")
{
return [...state, action.payload]
}
if(action.type == "UPDATE_TEAM")
{
const {team, point} = action.payload;
const changedIdx = state.findIndex((item) => item.team === team);
return [...state.slice(0, changedIdx), action.payload, ...state.slice(changedIdx + 1)]
}
return state;
}

Failed to store data in redux store

.created a store
.created actions and reducers
.connected store to my component
.failed to store data in redux store
i have to store the add events in a calendar using redux ,the values are not stored in redux .
// Actions
export const saveUserEvents=(events)=>{
return {
type:'SAVE_USER_EVENTS',
payload: events
}
}
//Reducers
export const form=(state = initialState, action) => {
switch (action.type) {
case "SAVE_USER_EVENTS":
return {...state, events: action.payload};
default:
return state
}
}
// Store
let reducers=combineReducers({
form
})
export default createStore(
reducers,
composeWithDevTools(
applyMiddleware(thunk)
)
)
// Component
Form(){
var title = document.getElementById("title").value
var description = document.getElementById("description").value
var start = document.getElementById("start").value
var end = document.getElementById("end").value
if(title!=""){
alert("Event Added Successfully")
this.props
.form({
variables: {
title:title,
description:description,
start:start,
end: end,
user_id: localStorage.getItem("id")
}
})
.then(({ data }) => {
alert("data is "+JSON.stringify(data.form))
if(data.form.message == "Event saved"){
this.props.saveUserEvents(data.form);
//alert("success")
//this.props.history.push('/Calender')
window.location.href="/Calendar";
return true;
}else {
alert("failure")
document.getElementById("messagegeneralNumber").innerHTML = '';
}
})
.catch(error => {
alert("data is "+JSON.stringify(error))
})
}
else{
alert("data not loading")
}
}
//connected to store-redux. using mapstatetoprops and mapdispatchtoprops
const mapStateToProps=(state, ownProps)=>{
return {
form: state
}
}
const mapDispatchToProps={
saveUserEvents
}
const Event = compose(
graphql(mutations.FORM,{name:'form'})
)(AddEvent);
export default withRouter(connect(mapStateToProps
,mapDispatchToProps)
(Event));
Your mapDispatchToProps should look like this:
const mapDispatchToProps = (dispatch) => {
saveUserEvents: (events)=>{
dispatch(saveUserEvents(events)); <--- here is your action creator that have to be dispatched
}
}

redux dispatch does not work

I am a redux beginner, everything is confusing for me right now. I am trying to create a store and dispatch a new value to the store, but it does not work, can someone help? thanks
import {createStore, combineReducers} from 'redux';
import uuid from 'uuid';
const state={
id:0,
numbers:[]
}
const randomNumber=()=>{...}
//reducer
const reducer=(state={},action)=>{
switch(action.type){
case 'ADD_NUMBER':
const newNumber={id:state.id+1, number:randomNumber()}
return {
...state,
id:uuid(),
numbers:[...state.numbers,newNumber]
}
}
}
//store
const store=createStore(reducer)
store.subscribe(()=>{const state=store.getState})
console.log('new state should update, but it does not: ', state)
const addNumber =()=>({type: 'ADD_NUMBER'})
//dispatch
store.dispatch(addNumber())
this is my error
Issue is in this line,
const reducer = (state = {}, action) => {
Note that you have initialized your state to an empty object {}. So when you try to spread the state.numbers you are getting this error because numbers is not defined in the initial state.
return {
...state,
id:uuid(),
numbers:[...state.numbers,newNumber]
}
A minimal example that reproduces your issue,
const bad = (state = {}) => {
return {
numbers:[...state.numbers]
}
}
bad();
To fix this you'll need to initialize your state with the default values,
const INITIAL_STATE = {
id:0,
numbers:[]
}
//reducer
const reducer = (state = INITIAL_STATE, action) => {
// Rest of the code
const INITIAL_STATE = {
id:0,
numbers:[]
}
const good = (state = INITIAL_STATE) => {
return {
numbers:[...state.numbers]
}
}
console.log(good());

Resources