0

I have a functional component which I pass a function addEvent to, which takes an event parameter. However, when I call the function from props inside a functional component, the function doesn't execute:

const onOk = () => {
  const { title, description, start_time, end_time, remind_time } = formStates;
  const event = { 
    title:title[0], 
    description:description[0], 
    start_time:start_time.toISOString(),
    end_time: end_time.toISOString(),
    remind_time: remind_time.toISOString()
  }
  props.addEvent(event);
  props.hideModal();
};

const ModalConductor = props => {
switch(props.modal.currentModal) {
    case EVENT_FORM_MODAL:
        return <EventsFormModal {...props} title="New Event" addEvent={addEvent}/> 

    default:
        return null;
}
};

Passed Function:

export const addEvent = (event) => dispatch => {
console.log(event);
axios
    .post('/api/events/', event)
    .then(res => {
        dispatch({
            type: ADD_EVENT,
            payload: res.data
        });
    }).catch(err => console.log(err));
}

I have read on React docs that passing functions to components requires a this.function = this.function.bind(this);. However, there is no this in a functional component and there is no example in the docs. How would I fix this issue? Any help would be appreciated!

1 Answer 1

1

in your code ModalConductor is your functional component which takes props as input. you are accessing addEvent directly, instead of props.addEvent.

const ModalConductor = props => {
switch(props.modal.currentModal) {
    case EVENT_FORM_MODAL:
        return <EventsFormModal {...props} title="New Event" addEvent={props.addEvent}/> 

    default:
        return null;
}
};

also as long as your function definition doesn't contain 'this', you dont have to worry about 'this' binding.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.