0
votes

I am learning Redux. I am trying to connect dispatch function from container component to presentation component.

Container Component:

//FILE : app/javascript/packs/containers/registration.js 

import { connect } from 'react-redux'

import { fetchCountry } from '../actions'

import Countries from '../components/registration/countries';

const getCountry = (state, filter) => {
  switch (filter) {
  case 'region':
  console.log("Get Country Triggered",state)
  default:
  console.log("Get Country Default Triggered",state)
 }
}

const mapStateToProps = state => ({
  countries:getCountry(state,'region')
})

const mapDispatchToProps = dispatch => ({
  fetchCountry: region => dispatch(fetchCountry(region))
})

export default connect(
  mapStateToProps, 
  mapDispatchToProps
)(Countries)

Presentational Component

// FILE : /app/javascript/packs/components/registration/countries.jsx

import React from 'react'
import PropTypes from 'prop-types'

const Countries = ({ fetchCountry }) => (
  <ul>
    <li> 
     <button onClick={() => fetchCountry('region')}>Get Country</button> 
    </li>
  </ul>
)

Countries.propTypes = {
  fetchCountry: PropTypes.func.isRequired
}

Actions :

//FILE : /app/javascript/packs/actions/index.js

/* Action types */

export const FETCH_COUNTRY = "FETCH_COUNTRY";
export const FETCH_CITY = "FETCH_CITY";

/* Action creators */

export function fetchCountry(region) {
  return { type: FETCH_COUNTRY, region };
}

Reducer

// FILE: /app/javascript/packs/reducers/fetchPlace.js 

const fetchPlace = (state = [], action) => {
 switch (action.type) {
 case 'FETCH_COUNTRY':
  console.log('FETCH COUNTRY Reducer');
 default:
  return state
 }
}

export default fetchPlace

I am fetchCountry is undefined error when I try to load the page.

warning.js:33 Warning: Failed prop type: The propfetchCountryis marked as required inCountries, but its value isundefined.

I understand , i am missing some basics here, any help will be highly appreciated.

1
do you have a index file in your actions? - leogoesger
Is your actions.js in the right folder?, - Ignacio
You should try writing console.log(fetchCountry ) before const getCountry to see if its undefined or a function - Inus Saha
Thanks for quick reply, I check the file paths and its correct. I also updated the file paths. - Senthil

1 Answers

0
votes

Maybe this line is your problem. Depends on if you have an index.js

import { fetchCountry } from '../actions'

should be

import { fetchCountry } from '../actions/action_file_name'