I am working on a temperature control app with react native. To get the value of the temperature I use redux toolkit. My problem is that my code for increasing/decreasing the initial value with the reducers doesn't work. I get the 20 as value but using handlers to dispatch(in/decreaseTemp()) doesn't do anything. What am I doing wrong?
Reducers:
import { createSlice } from '@reduxjs/toolkit';
const initialStateValue = {
value: 20
}
const tempSlice = createSlice({
name: 'temp',
initialState: initialStateValue,
reducers: {
increaseTemp: (state = initialStateValue) => {
state = state + 1;
},
decreaseTemp: (state = initialStateValue) => {
state = state - 1;
}
}
});
export const {increaseTemp, decreaseTemp} = tempSlice.actions;
export default tempSlice.reducer;
The handlers:
function increaseTempHandler() {
dispatch(increaseTemp());
}
function decreaseTempHandler() {
dispatch(decreaseTemp());
}
The issue is a mismatch between how you've defined your state
const initialStateValue = {
value: 20
};
and how you're using it:
increaseTemp: (state = initialStateValue) => {
state = state + 1;
},
If state is an object that has a value property then your reducer should be returning a new state that has the updated value property.
e.g.
increaseTemp: (state = initialStateValue) => {
const { value } = state;
return { ...state, value: value+1 }
},