'Redux Toolkit useSelector not updating state in React component
I was reading through a few posts, but I can't seem to find the right way to approach my issue. I am using Redux Toolkit and dispatch() to update state in my game, but after that update, which is being successfully sent to Redux store (checked with devtools), changes are not being registered in the useSelector variable.
Here is my React component:
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { setDice } from './playareaSlice';
import './Playarea.css';
const Playarea = () => {
// This part here does not update the new state that is in my store after I dispatch my action
const dice = useSelector((state) => state.playarea.dice);
const dispatch = useDispatch();
const [currentPlayer, setCurrentPlayer] = useState(1);
const [attemptsLeft, setAttemptsLeft] = useState(3);
const rollDice = () => {
let newDice = dice.map((die) => {
return { ...die };
});
console.log('old state: ', dice);
for (let i = 0; i < newDice.length; i++) {
const randomValue = Math.floor(Math.random() * 6) + 1;
if (newDice[i].saved === false) {
newDice[i].value = randomValue;
}
}
dispatch(setDice(newDice));
};
// The rest of the code, simple JSX
And here are my store and component slice:
import { configureStore } from '@reduxjs/toolkit';
import scoreboardReducer from './features/scoreboard/scoreboardSlice';
import playareaReducer from './features/playarea/playareaSlice';
export const store = configureStore({
reducer: {
scoreboard: scoreboardReducer,
playarea: playareaReducer,
},
});
import { createSlice } from '@reduxjs/toolkit';
import { allDice } from '../../utils';
const initialState = {
dice: allDice,
};
export const playareaSlice = createSlice({
name: 'playarea',
initialState,
reducers: {
setDice: (state, action) => {
state.dice = action.payload;
},
},
});
export const { setDice } = playareaSlice.actions;
export default playareaSlice.reducer;
I would appreciate any help on how I could fix it!
Thank you!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
