I have some hook for fetching countries array from api :
import { useSelector, useDispatch } from 'react-redux'
const useCountries = () => {
const dispatch = useDispatch()
const { countries } = useSelector(data => data)
useEffect(() => {
if (!countries.length) {
dispatch(getCountries())
}
}, [countries])
return {
countries
}
}
I have some components which aren't on the same level of DOM , and aren't related to each other
const FirstComponent = () => {
const {countries} = useCountries()
// some using of countries array
}
const SecondComponent = () => {
const {countries} = useCountries()
// some using of countries array
}
When page loading 2 of these components, are executed, and 2 actions are dispatched. Because countries aren't selected yet in first and in the second component it calls API request. My question is, how can I prevent sending the second request if some request was sent. Make some rule for sending request only once, if try to send the second one, then block it. Or what is the correct solution or approach in my case?
Also, I've tried a case like this :
const {
external: { response, isInitial }
} = useSelector(data => data)
useEffect(() => {
if (!response && isInitial) {
dispatch(setIsInitial(false))
fetch()
.then(res => res.json())
.then(data => {
setResponse(data)
})
}
}, [dispatch, response, isInitial])
Here is my reducer :
const initialState = {
response: null,
isInitial: true
}
export default function external(state = initialState, action) {
switch (action.type) {
case types.SET_RESPONSE:
return {
...state,
response: action.payload.data
}
case types.SET_INITIAL:
return {
...state,
isInitial: action.payload.data
}
default:
return state
}
}
But it sends 2 requests