1

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?

Jay
  • 2,826
  • 2
  • 13
  • 28
Danilo Cunha
  • 1,048
  • 2
  • 13
  • 22

2 Answers2

1

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);

blueseal
  • 2,726
  • 6
  • 26
  • 41
  • 1
    Well done! I just don't know why use the "async dispatch" – Danilo Cunha Nov 12 '19 at 18:22
  • I need to add `async` if I need to use `async/await` instead of `then and catch`. `async/await` approach provides more readable code. please follow this https://stackoverflow.com/a/46118968/5124488 – blueseal Nov 12 '19 at 18:31
0

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)    
        }
Danilo Cunha
  • 1,048
  • 2
  • 13
  • 22