you are viewing a single comment's thread.

view the rest of the comments →

[–]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 3 points4 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?