I've been at this for a while and I can't figure it out. When I dispatch my populateDatasets action I can see that my store gets updated just fine in dev tools, but when I try to to access that state in a React component with useSelector it always returns undefined.
Here is how I've configured my store
import { configureStore } from '@reduxjs/toolkit'
import datasetReducer from './datasets'
export default configureStore({
reducer: {
datasets: datasetReducer
},
devTools: true
})
Here is the slice that I've created for this piece of state
import { createSlice } from '@reduxjs/toolkit'
export const datasetSlice = createSlice({
name: 'datasets',
initialState: [],
reducers: {
populateDataset: (state, action) => {
state.push(action.payload)
}
}
})
export const { populateDataset } = datasetSlice.actions
export default datasetSlice.reducer
And here is where I dispatch the action in my React component
const App = () => {
const { datasets } = useSelector((state) => state.datasets)
console.log('datasets: ' + datasets)
const dispatch = useDispatch()
useEffect(() => {
csv(FantraxHQData).then(data => {
data.map((player) => {
player.isDrafted = false
return player
})
dispatch(populateDataset(data))
})
csv(FantasyProsData).then(data => {
data.map((player) => {
player.isDrafted = false
return player
})
dispatch(populateDataset(data))
})
}, [])
return (
<div className={styles.outter}>
<MyTeam />
<div className={styles.container}>
<DataButtons />
<DraftBoard />
</div>
</div>
)
}
Again, my store updates just fine when I dispatch the action, but datasets is always undefined. Any help would be much appreciated.
Update Solution: The solution was to change { datasets } to datasets
Your datasets is an array in your redux store, but you're reading it as a object when
you're using useSelector(). Change the useSelector line to const datasets = useSelector((state) => state.datasets). Don't use the flower bracket on datasets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With