Objective: Access the latest data from a slice in my Redux store in response to user input.
Problem: I’ve tried const mySliceSelector = useSelector((state) => state.mySlice);
, but when the user input triggers my callback function, the actual state of mySlice is not accessible via my selector. I tested this by doing console.log(JSON.stringify(mySliceSelector))
, and it just prints the initial state of the slice. If I make a change to the file that contains this code and save it, everything works correctly after the hot reload.
Here is a snippet of my code, for better context:
const mySliceSelector = useSelector((state) => state.mySlice);
const handleClick = async () => {
console.log(JSON.stringify(mySliceSelector));
}
The arrays and data inside the slice are empty when printed, except after a hot reload.
Setup: I have a slice, which contains arrays and objects in its state. This slice can be changed from various actions taken by the user. On a specific page, I want to be able to display the entire contents of the slice to the user if they click a button. I attempt to JSON.stringify()
a selector I have for that slice (see above), but it prints the initial state unless I trigger a re-render of the page where this button lives.
2
Answers
The solution My problem did not require me to subscribe to state updates for the slice. Thus,
useSelector()
was unhelpful. After looking over the documentation again, I found useStore(). The following line of code allows me to read the current state of an entire slice, which I then print out in response to a click event:You’r questions is not clear do you want to access the whole data of you’r store if so you can just access like this.
regarding your issue it’s better you put the whole context when are you calling this call back which you are referring
handleClick
ideally you should get the latest data but for some reason if it’s not their try to check the flow of you’r component logic.