Elvaleryn
Elvaleryn

Reputation: 351

React Redux cannot pass props of a functional component

What im trying to achieve in here is to being able to click on a image and render that clicked movie’s info. The problem is the i can not find a way to match id of the clicked movie and the detailed movie. As a result the singleMovierequest has undefined id which causes 404 error. Here is codesandbox link: https://codesandbox.io/s/modern-http-coy0w (Api key is typed as '???' intentionally). Here is movie and app components.

const Movie = (props) => {

const movie = props.singleMovie
const fetchMovie = props.initializeSingleMovie
useEffect(() => { fetchMovie(props.id) }, [props.id]) 

return (
    <div>
        <h2>{movie.title}</h2>
        <p>{movie.overview}</p>
    </div>
)

} render part of the app component:

<Container>
        <h2>Movieapp</h2>
        <Router>
            <Menu />
            <Route exact path="/popular" render={() =>
                <PopularMovies />
            } />
            <Route exact path="/search" render={() =>
                <Movies />
            } />
            <Route exact path="/search/:id" render={(props) => <Movie key={props.match.params.id} />} />
            } />
            <Route exact path="/popular/:id" render={(props) => <Movie key={props.match.params.id} />} />
        </Router>

    </Container>

Upvotes: 0

Views: 565

Answers (1)

warmachine
warmachine

Reputation: 376

"initializeSingleMovie" is an action,You named it reducer but its an action,for the sake of solving this problem ,you have to use mapDisptachToProps and dispatch(it will access the store methods),below is a modifed Movie.js File.In future have a separate action folder for api hits.Compartmentalise more,hope it helps.

import React from 'react'
import { connect } from 'react-redux'
import { useEffect } from 'react'
import { initializeSingleMovie } from '../reducers/singleMovieReducer'


const Movie = (props) => {

    console.log(props,"");


    const movie = props.singleMovie
    props.initializeSingleMovie(props.id)


    return (
        <div>
            <h2>{movie.title}</h2>
            <p>{movie.overview}</p>
        </div>
    )
}

const mapStateToProps = (state) => {
    return {
        singleMovie: state.singleMovie
    }
}
const mapDispatchToProps = dispatch => {
   return {
   initializeSingleMovie: (id) => dispatch(initializeSingleMovie(id)),

   };
}; 

export default connect(
    mapStateToProps,
    mapDisptachToProps
)(Movie)

Upvotes: 1

Related Questions