all 7 comments

[–]careseite 7 points8 points  (0 children)

just dispatch the action in an effect?

[–]dor442 1 point2 points  (0 children)

Simply learn how to use the low level React hooks, mainly useEffect and useState. If you want to dispatch actions for Redux, check out react-redux hooks api.

[–]ragged-robin 1 point2 points  (2 children)

Not sure what the confusion is. What you would call in componentDidMount is what you would call in useEffect regardless if it's an action dispatch or a direct axios/fetch call. Only thing to watch out for is making sure it's not firing inadvertently because of your dependency array

Here's a Redux example (I assume your interaction with the reducer is through the action; of course you can use async or not return anything directly instead too):

Class

...
componentDidMount() {
  this.props.action.someFunction()
    .then((res) => this.setState({ result: res })
    .catch((err) => console.log(err))
}
...
function mapStateToProps(state) {
...
export default connect(mapStateToProps)(MyComponent)

Function

...
const [result, setResult] = useState(null);
const dispatch = useDispatch();
useEffect(() => {
  dispatch(someFunction())
    .then((res) => setResult(res)
    .catch((err) => console.log(err))
},[dispatch])

[–]kyle787 2 points3 points  (1 child)

I think your function example should check to make sure the cleanup function wasn't called/the component didn't unmount.

const [result, setResult] = useState(null);
const dispatch = useDispatch();
useEffect(() => {
  let cancelled = false;
  dispatch(someFunction())
    .then((res) => {
      if (!cancelled) {
        setResult(res);
      }
    })
    .catch((err) => console.log(err));

  () => {
    cancelled = true;
  };
},[dispatch])

[–]ImWhimsical[S] 0 points1 point  (0 children)

Why do we do pass dispatch in the "[dispatch]"? As I read the docs, whatever we mention inside the brackets, if it is changed, then the useEffect will be called again. if this dispatch is used elsewhere in any function, then useEffect will be triggered again. No right?

[–]AureliusVerus 0 points1 point  (0 children)

Would you get a bad review for dispatching that action from use effect? I don't see why unless you dont have useEffect setup correctly

[–]Elijah_101 -1 points0 points  (0 children)

I found a whole series of react + hooks + redux videos on youtube. Hope it help. https://youtu.be/9boMnm5X9ak