I have several components that require access to the same list of players. This list of players won't change, but I do not know what component will required it first. My idea here is that whoever component requires it first (axios request) updates my redux store and then the other ones would just use this same custom hook for that.
export default function usePlayersList() {
const {list, loading, error} = useSelector(state => state.accounts.players)
const dispatch = useDispatch()
useEffect(() => {
try {
const response = authAxios.get(endpoints.players.retrieve)
response.then(res => {
dispatch({
type: "SET_PLAYERS_LIST",
payload: {
error: false,
loading: false,
list: res.data.payload
}
})
})
} catch (e) {
console.log(e)
dispatch({
type: "SET_PLAYERS_LIST",
payload: {
error: true,
loading: false,
list: []
}
})
}
}, [dispatch])
return {list, loading, error}
}
This is my custom hook for that. Wondering if there is any inconvenience with doing that or even better patterns for such. Thanks in advance.
BTW... Even better, I would set loading and error as useState variables inside my usePlayersList (as opposed to sending them to redux state). Since this lead me to error (loading and error became different on each component, assuming that this state became individual to each component) I sent them to store.
Best regards, Felipe.