RTK Query: Refetch when global state changes #3304
-
Greetings, Every time my global state Basically what I want to happen is:
apiSliceexport const newsApi = createApi({
reducerPath: 'newsApi',
baseQuery: fetchBaseQuery({ baseUrl: 'https://api/' }),
endpoints: (builder) => ({
getNews: builder.query<News, void>({
query: () => `top?apiKey=${API_KEY}`,
keepUnusedDataFor: 30
}),
getNewsByCountry: builder.query<News, void>({
queryFn: async (_, { getState }) => {
console.log('getNewsByCountry queryFn called.');
const state = getState() as RootState;
const country: string = state.selectedCountry.value.code;
const response = await fetch(
`articles?country=${country}&apiKey=${API_KEY}`
);
if (!response.ok) {
throw new Error('Failed to fetch news.');
}
const data: News = await response.json();
return { data: data as News };
}
})
})
}); SelectedCountrySliceexport const selectedCountrySlice = createSlice({
name: 'selectedCountry',
initialState: {
value: {
code: 'us',
name: 'United States'
}
},
reducers: {
setSelectedCountry: (state, action: PayloadAction<Country>) => {
state.value = action.payload;
}
},
extraReducers(builder) {
builder.addMatcher(
(action) => action.type === setSelectedCountry.type,
(state, action) => {
console.log('Selected country changed.');
}
);
}
});
export const { setSelectedCountry } = selectedCountrySlice.actions;
export const selectedCountry = (state: any) => state.selectedCountry.value; |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
The usual suggested pattern is to do this at the component level with the hooks: const someValue = useSelector(selectSomeValue);
const { data } = useSomeQuery(someValue); That way the query hook will re-run and fetch a new result every time If you're doing that in many components, you could extract those lines into a custom hook and use that. |
Beta Was this translation helpful? Give feedback.
The usual suggested pattern is to do this at the component level with the hooks:
That way the query hook will re-run and fetch a new result every time
someValue
changes.If you're doing that in many components, you could extract those lines into a custom hook and use that.