lpetrucci
lpetrucci

Reputation: 1679

Connect a normal function to Redux's mapDispatchToProps

I'm getting my head around Redux and while I understand how it functions I'm not entirely sure if I'm using it correctly.

The Redux Documentation gives plenty of example on how to connect a functional component to my actions. But is there any way to call my action directly from within a function?

Is it possible to get something like this to work?

function mapDispatchToProps(dispatch) {
  return {
    saveUserData: user => dispatch(saveUserData(user))
  };
}

function ConnectedUserInfo(){
  console.log("fetching user info")
  fetch('endpoint', 'headers',
  }).then(response =>
    response.then(user => {
      this.props.saveUserData(user)
    })
  )
}

const getUserInfo = connect(
  null,
  mapDispatchToProps
)(ConnectedgetUserInfo);
export default getUserInfo;

I tried setting my redux state directly with saveUserData(user) but couldn't get the Store to change. Connecting the two doesn't seem to do anything, unless I'm doing something wrong.

I'm unsure if this is the solution I'm looking for or if Redux wants me to mapDispatchToProps every time I want to change the state.

Upvotes: 0

Views: 572

Answers (2)

Ayyappa Gollu
Ayyappa Gollu

Reputation: 966

if you read the react redux documentation , you can see that connect method returns an HOC which accepts only react components. in your code ConnectedgetUserInfo is not a react compoenent.

react-redux documentation: react-redux

react component defintion: https://reactjs.org/docs/react-component.html

also you have to name react component with starting character Capital.

Upvotes: 1

RamTn
RamTn

Reputation: 99

I recommend instead of mapdispatch or mapstate use useDispatch and useSelector from react-redux for functional components

import {useSelector,useDispatch} from 'react-redux;

const dispatch=useDispatch();
const stateSelector=useSelector(state=>({
    your states
}));

Upvotes: 0

Related Questions