简体   繁体   中英

How can I make an action be reusable? ReactJS with Redux

I need to do a dynamic action. In other words, it can be reused for differents actions.

I tried to create a function that loads type and payload, but an error appears.

I'm trying make this function works:

        export function getData(url, type) {
            const request = Server.get(url)

            return (dispatch) =>
            request.then((response) => {  
                    dispatch({
                        type: type,
                        payload: response.data
                    })
                }).catch(function (error) {
                    console.log(error)
                });
        }

But I got an error when I call this function this way:

        export function getClientes() {
            Actions.getData('ClientesEFornecedores', GET_CLIENTES)    
        }

It's showing:

        Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.

I'm Calling the getClientes() function this way:

        function ClientesTable(props)
        {
            const dispatch = useDispatch();
            const clientes = useSelector(({erpCliente}) => erpCliente.clientes.data);

            useEffect(() => {
                dispatch(Actions.getClientes());
            }, [dispatch]);

How can I make an action be reusable?

Try something like this

export const getData=(url, type) =>async dispatch=>{

        try{
           const response = await Server.get(url);

           dispatch({ type: type,payload: response.data })

        } catch(err){
            console.log(err)
        }
    }

getClientes function

export const getClientes=() => dbActions.getData('ClientesEFornecedores', GET_CLIENTES);

In fact I had almost succeeded. All that remained was to return the function call.

This is the way that works:

        export function getClientes() {
            return dbActions.getData('ClientesEFornecedores', GET_CLIENTES)    
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM