I have the following component in my reactjs application:
import React, { useEffect } from 'react';
import { Helmet } from 'react-helmet';
import { connect } from 'react-redux';
import MovieList from '../components/MovieList';
import styled from 'styled-components';
import { getMoviesDiscover} from '../actions';
const Wrapper = styled.div`
display: flex;
width:100%;
flex-direction: column;
`;
const Discover = ({
geral,
movies
}) => {
const query = 'popular';
useEffect( () => {
getMoviesDiscover( query );
} , [] );
if( movies.loading ) {
return (
<div>
Movies are loading..
</div>
)
}
return (
<Wrapper>
<Helmet>
<title>Danm Gurl</title>
</Helmet>
<MovieList
movies={ movies }
/>
<MovieList
movies={ movies }
/>
</Wrapper>
)
}
const mapStateToProps = ({ geral, movies }) => {
return { geral, movies };
};
export default connect(
mapStateToProps,
{ getMoviesDiscover }
)(Discover);
As you can see i am using the React Hook useEffect like so ::-
useEffect( () => {
getMoviesDiscover( query );
} , [] );
The problem is if i add a console.log inside the useEffect
, i see the console.log in console. But the function getMoviesDiscover
is never executed. The getMoviesDiscover function is in an external file and looks like below:
export const getMoviesDiscover = ( name , page ) => async ( dispatch , getState ) => {
console.log('OK !')
dispatch({ type : 'FETCH_MOVIES_LOADING' })
const res = await tmdbAPI.get(`https://api.themoviedb.org/3/movie/${name}?api_key=<MY_API_KEY>` , {
params: {
page
}
});
await dispatch({
type: 'FETCH_MOVIES_DISCOVER',
payload: res.data
});
dispatch({ type : 'FETCH_MOVIES_FINISHED' })
}
Why is my useEffect Hook not invoking the function ?
So right now what's happening is that the imported (thunk)function getMoviesDiscover
from '../actions' is being called directly rather that the one that's passed into mapDispatchToProps
. So you will need to destructure this function in your props, e.g.
({
geral,
movies,
getMoviesDiscover
}) => {
You may also need to do getMoviesDiscover as myNewFuncName
to avoid shadow variable errors