const handleFilter = (filter_type, selection) => {
dispatch({ type: filter_type, option: selection.option })
filterData()
}
I have a useReducer
that handles the selected filter. I have to call the filterData
which filters the data based on the selected filter.
However, since it is not guaranteed for the filterData
to occur after the dispatch, I keep getting delayed update in the state.
I also tried
const handleFilter = (filter_type, selection) => {
dispatch({ type: filter_type, option: selection.option })
.then(filterData())
}
But this gave me an error Cannot read property 'then' of undefined
.
Any help?
EDIT
useEffect(() => {
const urls = [
'http://.../v1/profiles',
];
const fetchJson = url => fetch(url, get_options).then(res => res.json());
Promise.all(urls.map(fetchJson))
.then(([profile]) => {
setFilteredTable(profile.result)
})
.catch(err => {
console.log(err)
});
}, []);
const init_filter = { TITLE: '', LOCATION: '' }
const [filter, dispatch] = useReducer((state, action) => {
switch (action.type) {
case 'TITLE':
return { ...state, TITLE: action.option }
case 'LOCATION':
return { ...state, LOCATION: action.option }
case 'RESET':
return init_filter
default:
return state
}
}, init_filter)
I have to call the
filterData
which filters the data based on the selected filter.
You describing a listener, you can try using a useEffect
hook:
const [filter, dispatch] = useReducer(optionsReducer, initialValue);
useEffect(() => {
filterData();
}, [filter]);
const handleFilter = (filter_type, selection) => {
dispatch({ type: filter_type, option: selection.option });
};
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