pipikej
pipikej

Reputation: 305

React Redux - on submit wont fire action

I am trying to fire the Redux action on form submit in React but it does nothing and it does not show any errors at all.

action:

export const addLead = (lead) => (dispatch) => {
const url = 'http://localhost:8000/api/leads/'
axios.post(url, lead)
    .then(res => {
        dispatch({
            type: ADD_LEAD,
            payload: res.data
        });
    }).catch(err => console.log(err));

};

reducer :

      case "ADD_LEAD":
      return {
          ...state,
          leads: [...state, action.payload]
      }

And here is my Form component:

const Form = () => {

const [formData, setFormData] = useState({
    name: '',
    email: '',
    message:''
})

const {name, email, message} = formData;

const onChange = (e) => {
    setFormData({...formData, [e.target.name]: e.target.value});
}

const onSubmit = (e) => {
    e.preventDefault();
    console.log("submit")
    const {name, email, message} = formData;
    const lead = {name, email, message}
    console.log('Leads: ',lead)
    addLead(lead)
}

return(
   <form onSubmit={onSubmit}>
      .... Form .... 
   </form>

export default connect(null, {addLead})(Form);

If I submit the form in the Redux dev tools I dont see the action nor any error in the console. I can see the correct data in the states in the console.log and also the 'submit' so the function onSubmit is fired. Any idea why it is not working?

Upvotes: 0

Views: 154

Answers (2)

Louay Al-osh
Louay Al-osh

Reputation: 3405

@Nick is right, we didn't see the full component code to judge where addLead comes from.

1- addLead need to be use consumed from component props(which is wired down using react-redux connect higher order function)

2- for async actions I see you are using a thunk but you maybe forgot to return when you call axios inside the thunk.


export const addLead = (lead) => (dispatch) => {

    const url = 'http://localhost:8000/api/leads/';

    return axios.post(url, lead)
        .then(res => {
            dispatch({
                type: ADD_LEAD,
                payload: res.data
            });
        })
        .catch(err => console.log(err));
}

Upvotes: 0

Nick
Nick

Reputation: 16576

You need to use addLead from props, meaning you need to make sure you're grabbing it from the props argument of your Form component:

const Form = ({addLead}) => {
  // Component code stays the same
}

It's important to remember that connect will map state to props and map dispatch to props.

Upvotes: 3

Related Questions