1

Here's my login action code. What am I doing wrong ? As you can see, reducer state update not called.

Please, help me guys!

React - 16.8 Axios Http Client Node & Mongo Db Backend

export const loginUser = (userData) => {
    axios.post(URL + '/api/admin/login', userData)
        .then(res => {
            return {
                type: SIGNIN_USER,
                payload: storeData
            }

        })
        .catch(err => {
            return {
                type: SHOW_MESSAGE,
                payload: err.response.data
            }
        });
};
Sergey
  • 995
  • 4
  • 14
  • 33

4 Answers4

1
    .then(res => {
        return {
            type: SIGNIN_USER,
            payload: storeData
        }

    })

Instead of returning res, apply an action to it here. You mentioned changing the state, so something similar:

    .then(res => {
        this.state.someResult = res;
    })
Horatiu Jeflea
  • 7,256
  • 6
  • 38
  • 67
1

You need to dispatch the action, not just return the object:

const dispatch = useDispatch(); // Assuming you're inside functional component

export const loginUser = (userData) => {
    axios.post(URL + '/api/admin/login', userData)
        .then(res => {
            return dispatch({
                type: SIGNIN_USER,
                payload: storeData
            })

        })
        .catch(err => {
            return dispatch({
                type: SHOW_MESSAGE,
                payload: err.response.data
            })
        });
};
Clarity
  • 10,730
  • 2
  • 25
  • 35
1

Try with this code sample :

export const loginUser = userData => dispatch => (
    axios.post(URL + '/api/admin/login', userData)
        .then(res => dispatch({ type: SIGNIN_USER, payload: res }))
        .catch(err => dispatch({ type: SHOW_MESSAGE, payload: err.response.data }))
)
Hemant
  • 170
  • 2
  • 11
  • I tried this , but failed . Error like action must be a object – Sathis Sakthivel Oct 10 '19 at 12:51
  • this means you are not dispatch the function from the component in a right way. – Hemant Oct 10 '19 at 12:54
  • checkout this link and follow the right way to call the action in component. https://medium.com/backticks-tildes/setting-up-a-redux-project-with-create-react-app-e363ab2329b8 – Hemant Oct 10 '19 at 12:58
0

Make use of Arrow functions it improves the readability of code. No need to return anything in API.fetchComments, Api call is asynchronous when the request is completed then will get the response, there you have to just dispatch type and data.

Below code does the same job by making use of Arrow functions.

export const bindComments = postId => {
  return dispatch => {
    API.fetchComments(postId).then(comments => {
      dispatch({
        type: BIND_COMMENTS,
        comments,
        postId
      });
    });
  };
}; 

reference link : React-Redux: Actions must be plain objects. Use custom middleware for async actions