0

I have a component where I want to dispatch a Redux action through a function. What I do not understand is, the function is not executed. A console.log() right before and after the functioncall bar() gets logged, but when I try to console.log() from the function bar(), that has no effect what so ever... Why is that?

// Foo.js
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import React from 'react';
import { bar } from './actions';

const Foo = () => {
    useEffect(() => {
    console.log('I get logged');
        bar();
    console.log('I get logged too');
    }, [])

    return <Whatever> ... </Whatever>
};


const mapDispatchToProps = dispatch => {
    return bindActionCreators({
        bar,
    }, dispatch)
};

const mapStateToProps = state => {
    const { ... } = state
    return {
        ...: ...
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(Foo);




// actions.js
export const bar = () => async dispatch => {
    console.log('I do not get logged');
    await ... 
    dispatch({ type: ..., ... });
};

1 Answer 1

1

Because bar at this point references your unbound action creator, not the one from connect. You would have to use props.bar to get that. But you should not.

Generally, you should not use connect with function components, but the useDispatch and useSelector react-redux hooks instead.

So it should look like

const Foo = () => {
    const dispatch = useDispatch();
    useEffect(() => {
    console.log('I get logged');
        dispatch(bar());
    console.log('I get logged too');
    }, [dispatch])

    return <Whatever> ... </Whatever>
};

without any use of connect anywhere.

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.