3

I'm just learning Redux and I have a problem.

I have actions:

export const getValues = () => async (dispatch) => {
    try {
        const res = await axios.get(`/values`);
        dispatch({
            type: VALUE_STATE,
            payload: res.data,
        });
    } catch (err) {
        console.log(err);
    }
};
    
    
export const getUsers = () => async (dispatch) => {
    try {
        const res = await axios.get(`/users`);
        dispatch({
            type: ALL_USER,
            payload: res.data,
        });
    } catch (err) {
        console.log(err);
    }
};

COMPONENT

const handleClick = () => {
    dispatch(getValues());
    dispatch(getUsers());
};

Why, when I dispatch, they are triggered in the wrong order, sometimes in the right order ?

Triko42
  • 31
  • 2
  • 1
    you have an asynchronous function axis.get() in your calls. Meaning it will have to finish your get request before calling the dispatch. Your sequence will then be dependent on your get request completion order. – Someone Special Nov 21 '20 at 17:50

1 Answers1

1

use batch to set them by order in one state update:

const handleClick = () => async {
     await getValues();
     await getUsers();
};
Or Assayag
  • 5,662
  • 13
  • 57
  • 93
  • 1
    it works, but vs code told me "await' has no effect on the type of this expression – Triko42 Nov 21 '20 at 18:54
  • Glad to help. On which statement you get this warning? Can you add image / specific code of warning? – Or Assayag Nov 21 '20 at 18:58
  • const handleClick = () => { dispatch(getValues()).then(() => dispatch(getUsers())); }; is it good practice ? what do you think ? – Triko42 Nov 21 '20 at 19:10
  • I would rather do as I answer, it's better practice. I need the full code to help you with the warning. – Or Assayag Nov 21 '20 at 19:12
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/224901/discussion-between-orassayag-and-triko42). – Or Assayag Nov 21 '20 at 19:28