//state.buttons is an array - it is used to map buttons to a menu
function NavMenu() {
const buttons = useSelector((state) => state.buttons);
const dispatch = useDispatch();
const navButtons = buttons.map((button) => {
const checkDirection = (button) => {
if (button.pageNo >= button.prevPageNo) {
dispatch(updateButtonsData({ newDirection: 1 }));
} else {
dispatch(updateButtonsData({ newDirection: -1 }));
}
};
checkDirection(button);
return (
<li key={button.id} >
<NavButton buttonData={button} />
</li>
);
});
return <ul>{navButtons}</ul>;
}
export default NavMenu;
//buttonSlice
const initialState = [
{
id: 'homeId',
prevPageNo: null,
pageNo: 1,
direction: 1,
firstAnimFrame: 1,
lastAnimFrame: 1,
},
{
id: 'aboutId',
prevPageNo: null,
pageNo: 2,
direction: 1,
firstAnimFrame: 1,
lastAnimFrame: 11,
},{...}
const buttonsSlice = createSlice({
name: 'ui',
initialState,
reducers: {
updateButtonsData: {
reducer(state, action) {
state = action.payload;
},
prepare(
id,
newPrevPageNo,
pageNo,
newDirection,
newFirstFrame,
newLastFrame
) {
return {
payload: {
id,
prevPageNo: newPrevPageNo,
pageNo,
direction: newDirection,
firstAnimFrame: newFirstFrame,
lastAnimFrame: newLastFrame,
};},},},},});
Hello, I have a navigation menu where several parameters must be dynamically updated within the UI when a user presses a button. Each button will behave differently depending on the previous button as pressed (order of pressed buttons matters). My solution is to compare the initial state of the nav buttons array to each subsequent remapping. I thought it would be good to store the history of the previously pressed button as a value inside the nav objects array. Each time the navigation is refreshed, new parameters are added and accessible as props inside the mapped button and can then be accessed onClick.
Currently, the dispatch function does not work with my code, and the mapped buttons array remains unchanged.
I assume that you are "triggering" the update data via checkDirection(button); and not onClick Event.
first this is a "no-go" code:
const navButtons = buttons.map((button) => {
const checkDirection = (button) => {
if (button.pageNo >= button.prevPageNo) {
dispatch(updateButtonsData({ newDirection: 1 }));
} else {
dispatch(updateButtonsData({ newDirection: -1 }));
}
};
checkDirection(button);
return (
<li key={button.id} >
<NavButton buttonData={button} />
</li>
);
});
return <ul>{navButtons}</ul>;
}
If you want to trigger a function while rendering an element, put it inside useEffect and not "outside".
So, transfer that code inside NavButton like:
const checkDirection = useCallback(button) => {
if (button.pageNo >= button.prevPageNo) {
dispatch(updateButtonsData({ newDirection: 1 }));
} else {
dispatch(updateButtonsData({ newDirection: -1 }));
}
}, []);
useEffect(() => checkDirection(button), [checkDirection, button]);