I have the following functional component. I did debugging and read some posts about react-redux and useEffect, but still have had no success. On initial render the state in my redux store is null but then changes to reflect new state with data. However, my react UI does not reflect this. I understand what the issue is, but I don't know exactly how to fix it. I could be doing things the wrong way as far as getting the data from my updated state in the redux store.
Here is my component :
const Games = (props) => {
const [gamesData, setGamesData] = useState(null)
const [gameData, setGameData] = useState(null)
const [gameDate, setGameDate] = useState(new Date(2020, 2, 10))
const classes = GamesStyles()
// infinite render if placed in
// useEffect array
const {gamesProp} = props
useEffect(() => {
function requestGames() {
var date = parseDate(gameDate)
try {
props.getGames(`${date}`)
// prints null, even though state has changed
console.log(props.gamesProp)
setGamesData(props.gamesProp)
} catch (error) {
console.log(error)
}
}
requestGames()
}, [gameDate])
// data has not been loaded yet
if (gamesData == null) {
return (
<div>
<Spinner />
</div>
)
} else {
console.log(gamesData)
return (
<div><p>Data has been loaded<p><div>
{/* this is where i would change gameDate */}
)
}
}
const mapStateToProps = (state) => {
return {
gamesProp: state.gamesReducer.games,
}
}
const mapDispatchToProps = (dispatch) => {
return {
getGames: (url) => dispatch(actions.getGames(url)),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Games)
Here is my reducer
import {GET_GAMES} from '../actions/types'
const initialState = {
games: null // what we're fetching from backend
}
export default function(state = initialState, action){
switch(action.type){
case GET_GAMES:
// prints correct data from state
//console.log(action.payload)
return{
...state,
games: action.payload
}
default:
return state
}
}
Here is my action
import axios from 'axios'
import {GET_GAMES} from './types'
// all our request go here
// GET GAMES
export const getGames = (date) => dispatch => {
//console.log('Date', date)
axios.get(`http://127.0.0.1:8000/games/${date}`)
.then(res => {
dispatch({
type: GET_GAMES,
payload: res.data
})
}).catch(err => console.log(err))
}
When I place the props from state in my dependencies array for useEffect
, the state updates but results in an infinite render because the props are changing.
This happens even if I destruct props.
Here is an image of my redux state after it is updated on the initial render.
isLoading
variable in your local state and renderprops.gameData
whenisLoading
becomes false – A. Ecrubit