javascriptreactjsredux

Redux Store - Access entire slice


Objective: Access the latest data from a slice in my Redux store in response to user input.

The Program: A React and Redux application, which has a button on a page. Upon being pressed, the button is meant to dump the state of a Redux slice to the user.

Problem: When user input triggers my onclick callback function, the actual state of mySlice is not accessible via my selector. I've tried const mySliceSelector = useSelector((state) => state.mySlice); and tested this by doing console.log(JSON.stringify(mySliceSelector)) inside the callback, and it just prints the initial state of the slice. Any changes that have been made to the slice since its conception are not shown.

Here is a snippet of my code, for better context:

    // mySlice is modified over time by other parts of the code
    const mySliceSelector = useSelector((state) => state.mySlice);
    
    const handleClick = async () => { // This is called by a button
        console.log(JSON.stringify(mySliceSelector));
    }

The arrays and data inside the slice are empty when printed as if haven't changed since the program started, even though they have changed.

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.


Solution

  • 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:

         import { useStore } from 'react-redux';
    ...
        const reduxStore = useStore();
        
        const handleClick = async () => {
            console.log(JSON.stringify(reduxStore.getState().mySlice));
        }