Deepak
Deepak

Reputation: 153

dispatching an action from componentDidMount

I have to fetch some data just after the component is mounted in react.i am using componentDidMount method and inside that i want to dispatch an action but when i am calling popular() (see code) it does nothing and if i do dispatch(popular()) it showns error that dispatch and popula not defined Please note that i have not used mapDispatchtoProps. What can i do to fetch the data ? Any help would be appreciated.

/action.js

export function popular(){
    return dispatch=>{
        return fetch(`https://api.themoviedb.org/3/movie/popular?api_key=<key>&language=en-US&page=1`)
                .then(data=>data.json())
                .then(data=>{
                        console.log("fetched",data);
                        dispatch({
                        type:"popular",
                        data:data.results,
                        page:data.page,
                        total_pages:data.total_pages,
                        total_results:data.total_results
                        })
     
                    })
    }
}

/App.js

import React from 'react';
import {Header} from './header.js';
import {Searchbar} from './searchbar.js';
import {Thumbnails}from './Thumbnails.js';
import {connect} from 'react-redux';
import {Select} from './select.js';
import { Pagination } from './pagination.js';
import {Filterbar} from './filterbar.js';
import { popular } from '../redux/action.js';

class App extends React.Component {
    componentDidMount(){
        console.log("heloo");
        popular();
           
        }

    render(){
        return (
            <>
                <Header /> 
                <Select {...this.props}/>
                <Filterbar/>
                <Searchbar {...this.props}/> 
                <Thumbnails {...this.props}/>
                <Pagination {...this.props}/>       
            </>
        );
    }
}

function mapStateToProps(state){
    return {
        state:state
    }
}

export default connect(mapStateToProps)(App)

Upvotes: 2

Views: 1076

Answers (1)

PasVV
PasVV

Reputation: 593

To dispatch the popular action you need provide redux-thunk middleware to redux and pass popular action through mapDispatchToProps.

Here an example:

componentDidMount() {
  this.props.getPopular();           
}

....

function mapDispatchToProps(dispatch) {
 return { getPopular: () => dispatch(popular()) };
}

Read more about that in the thunk docs. Also I recommend you refresh basics of redux. Just because you have some confuse. Naming and usage tell me about that.

Upvotes: 1

Related Questions