Mohammad
Mohammad

Reputation: 395

How do async redux functions work?

I started learning redux in reactjs. I am trying to implement an async structure to redux but I am really confused...

To implement an async function and use the promise you should type async before your function and use await before using the promise.

But in many examples I never saw they use of async before functions and await before the promise variables.

For example look at these two links:

https://redux.js.org/advanced/async-actions

https://github.com/reduxjs/redux/tree/master/examples/async

So how can I call async function in the reducer and return the async results?

For example, I want to prepare this list with an async function and get the list with axios or fetch API :

const list = [
    {id: 1, title: 'One'},
    {id: 2, title: 'Two'},
    {id: 3, title: 'Three'}
]

export function newsReducer(state = [], action) {
    switch (action.type) {
        case 'GET_NEWS':
            return list
        default:
            return state
    }
}

Upvotes: 1

Views: 170

Answers (2)

Abslen Char
Abslen Char

Reputation: 3135

One way to do it is to use redux-thunk like @ Sujit.Warrier suggested in the comment here is a small and simple example that can get you started using redux-thunk.

export const getlist =()=> dispatch =>{
   fetch(`api link for your list`).then(res => res.json())
            .then(data => {
              dispatch({type:'GET_NEWS' , payload:data})
            });
};

and then you can dispatch the function in your component

Upvotes: 2

Bogdan M.
Bogdan M.

Reputation: 2191

To summarize it I would suggest, to understand this concepts action, reducer and store.

  • An action is a trigger for one or more reducer cases
  • the store is on and all the data is contained and only reduceres can change it using the method they get from the store 'dispatch'
  • reducer is a piece of code that produces immutable changes on the store.

So in order to do a change to the store synchronically you have to call the store method dispatch such that the reducer triggers and changes what you expect.

To do async you will have to call the reducere when the async call is done.

Example:

   // action method called by react component when user submits changes
    export function updateProduct(product) {
        // returns a function since this method has to be called also with dispatch() in the component
        return dispatch => {
            // trigger first store change
            dispatch({ type: PRODUCT_EDIT.PRODUCT_EDIT_REQUEST });

            // trigger secod store change and mark the async call, updateProduct is ASYNC
            ProductsService.updateProduct(product)
                .then(
                    res => {
                        dispatch({ type: PRODUCT_EDIT.PRODUCT_EDIT_SUCCESS, data: res.data });
                        dispatch(successNotification('Product updated'));
                    },
                    error => {
                        dispatch({ type: PRODUCT_EDIT.PRODUCT_EDIT_FAILURE, data: error.response.data  });
                        dispatch(errorNotification(error.response.data));
                    }
                );
        };
    }

Other tutorials I think you should check: https://medium.com/@rajaraodv/step-by-step-guide-to-building-react-redux-apps-using-mocks-48ca0f47f9a

Upvotes: 2

Related Questions