Reputation: 8297
I have a redux action that fetches all data and stores it into a global Redux store.
I want to store that state in a local state using Hooks so that the actual state doesn't get changed when I change it locally.
What I am doing right now is,
const [filteredTable, setFilteredTable] = useState([])
useEffect(() => {
props.fetchDatabase();
props.fetchOptions();
setFilteredTable(props.filtered_table_data);
}, [])
In useEffect
, the props.fetchDatabase()
gets the props.filtered_table_data
and I can see that when I console.log it out.
However, when I use Hooks to store it into a local state and check if it's in there,
console.log(filteredTable, 'filteredTable')
just gives me []
.
What am I doing wrong?
Upvotes: 0
Views: 515
Reputation: 96
I believe the props.fetchDatabase()
call is asynchronous, so by the time you are attempting to setFilteredTable
the props.filtered_table_data
has not updated yet.
You can try something like this:
useEffect(() => {
props.fetchDatabase();
props.fetchOptions();
}, [])
useEffect(() => {
setFilteredTable(props.filtered_table_data);
}, [props.filtered_table_data]);
Note that this effect will run every time filtered_table_data
changes, so you may need to wrap around the code in the callback with some sort of condition if you want to restrict setting the local state.
Upvotes: 1
Reputation: 656
Not sure if this answers your question, but React-Redux provides some hooks for accessing the redux store.
The one that might be of interest to you is the useSelector()
hook.
Here's an example usage:
import { useSelector } from 'react-redux';
const App = () => {
const tableData = useSelector(state => state.tableData);
...
}
Upvotes: 0
Reputation: 339
useEffect
's callback with []
as hook's second argument is only being called once when component just mounted. Inside it fetchDatabase
, and fetchOptions
callbacks are called, and right after that (when data isn't yet fetched) you call setFilteredTable
, that's why there are empty array occurs in filteredTable
.
Upvotes: 0