Reputation: 307
Using the useState hook I update the state of the component (which I use to toggle an animation with react-spring) and I want to send the state's value to the redux store so I can use it on another component.
The problem is that while the useState hook works as expected, its value that gets passed as an argument to the action that gets dispatch is the opposite of the state.
Since the other component that gets the value from store still works fine (but always toggled on the opposite way) I assume it's not an action/reducer problem.
useState is initialised with false. on click updates the useState value. useState value is updated correctly. value then passed as an argument to a redux action which gets false instead of true.
export const UnconnectedMenuToggle: React.FC<INT.IToggleMenuProps> = ({
getToggleMenuRequest }): JSX.Element => {
const [isMenuOpen, setMenuOpen] = useState<boolean>(false);
const btnAnimation = useSpring<INT.IAnimateToggle>({
transform: isMenuOpen
? `translate3d(300px,0,0)`
: `translate3d(0px,0,0)`
});
const imgAnimation = useSpring<INT.IAnimateToggle>({
transform: isMenuOpen
? `rotate(0deg)`
: `rotate(540deg)`
});
const makeBoolGlobal = (): void => {
setMenuOpen(isMenuOpen => !isMenuOpen)
getToggleMenuRequest(isMenuOpen)
}
return (
<a.button
data-test="button-toggle"
className="menu-button"
onClick={makeBoolGlobal}
style={btnAnimation}
type="button"
>
<a.img src={chevron}
data-test="img-toggle"
alt="Open Menu"
style={imgAnimation}
/>
</a.button>
)
}
No error messages
Upvotes: 4
Views: 9154
Reputation: 340
Since the new hook setState method does not have callbacks you have to use useEffect to make functions after the state gets updated
const [count, setCount] = useState(0)
useEffect(() => doSth(count))
Upvotes: 4