Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to put a callback to useReducer's dispatch in React Hooks?

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)
like image 530
Dawn17 Avatar asked Oct 30 '19 21:10

Dawn17


1 Answers

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 });
};
like image 198
Dennis Vash Avatar answered Oct 05 '22 06:10

Dennis Vash