1

I'm trying to get data from api about currencies and I get error about NaN. I console.log(this.props) There it is: enter image description here

There is what I already did. In my actionTypes.js

export const FETCH_DATA_BEGIN = 'FETCH_DATA_BEGIN';
export const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
export const FETCH_DATA_FAIL = 'FETCH_DATA_FAIL';

and also there is my action.js

export const fetchData = () => {
  return dispatch => {
    fetch(`https://api.exchangeratesapi.io/latest?base=${this.props.base}`)
      .then(res => res.json())
      .then(
        data => dispatch(fetchDataSuccess(data)),
        e => dispatch(fetchDataFail(e)),
      );
  };
};

next is my initialState in my reducer and case actionTypes.FETCH_DATA_SUCCESS

const initialState = {
  currencies: ['USD', 'AUD', 'SGD', 'PHP', 'EUR', 'PLN', 'GBP'],
  base: 'EUR',
  amount: '',
  convertTo: 'PLN',
  result: '',
  date: '',
  error: null,
  loading: false,
  rates: '',
};
case actionTypes.FETCH_DATA_SUCCESS:
      const date = action.data.date;
      const rates = action.data.rates;
      return {
        ...state,
        date,
        rates,
        loading: false,
      };

next I'm using mapStateToProps and mapDispatchToProps in my component like this

const mapStateToProps = (state, ownProps) => {
  return {
    base: state.base,
    amount: state.amount,
    convertTo: state.convertTo,
    result: (state.rates[ownProps.convertTo] * ownProps.amount).toFixed(4),
    date: state.date,
  };
};

const mapDispatchToProps = dispatch => {
  return {
    handleFirstSelect: itemValue =>
      dispatch(exchangeCurriencesActions.handleFirstSelect(itemValue)),
    handleSecondSelect: itemValue =>
      dispatch(exchangeCurriencesActions.handleSecondSelect(itemValue)),
    handleInput: text => dispatch(exchangeCurriencesActions.handleInput(text)),
    fetchData: () => dispatch(exchangeCurriencesActions.fetchData()),
  };
};

And my componendDidMount() function is like that

componentDidMount() {
    if (this.props.amount === isNaN) {
      return;
    } else {
      try {
        this.props.fetchData();
      } catch (e) {
        console.log('error', e);
      }
    }
  }

And for example I'm using new props like this

 <TextInputComponent
              editable={false}
              value={`${
                this.props.amount === ''
                  ? '0'
                  : this.props.result === null
                  ? 'Calculating...'
                  : this.props.result
              }`}
            />

and of course I added middleware

export default class App extends React.Component {
  render() {
    const store = createStore(exchangeCurrencies, applyMiddleware(thunk));
    return (
      <Provider store={store}>
        <NavigationContainer>
          <StatusBar hidden={true} />
          <MainTabNavigator />
        </NavigationContainer>
      </Provider>
    );
  }
}

I'm adding a picture how does it look like in app

enter image description here

Where is the mistake? I can also add more code if its necessary. Please help someone !:D

  • Can you console log it `(state.rates[ownProps.convertTo] * ownProps.amount).toFixed(4)`? – ParthS007 Mar 06 '20 at 14:15
  • `state.rates[ownProps.convertTo]` probably gives you `undefined`. and `undefined` * number = `NaN` – dw_ Mar 06 '20 at 14:16
  • you're right. It gives me a NaN. Do you know how to fix it? ;/ – Daniel Gola Mar 06 '20 at 14:19
  • Since you have `convertTo` and 'amount' in state, you probably no longer need `ownProps`, use the state values instead. Also, can you log the `action.data` in the reducer's success case and see if it has the correct `date` and `rates`? – giotskhada Mar 06 '20 at 14:21
  • like that? ```case actionTypes.FETCH_DATA_SUCCESS: console.log(action.data); return { ...state, date: action.data.date, rates: action.data.rates, loading: false, };``` – Daniel Gola Mar 06 '20 at 14:30
  • well in this case it shows nothing in the console – Daniel Gola Mar 06 '20 at 14:31
  • That means the success action is never dispatched. So the fetch either fails or is never called. Can you log before `fetch()` and also inside the reducer for the fail action? – giotskhada Mar 06 '20 at 15:09
  • I think I'm doing something wrong. Still nothing shows in the console – Daniel Gola Mar 06 '20 at 15:28
  • To get more help I send a link how this application looked before (my app is in react-native not reactjs) https://codesandbox.io/s/3y77o7vnkp – Daniel Gola Mar 06 '20 at 15:31
  • mayble this will help us to figure out the problem – Daniel Gola Mar 06 '20 at 15:31
  • Ok, I guess `if (this.props.amount === isNaN)` this returns true when the component mounts, so `fetchData()` is never called. I'm guessing you should be listening to the change in `this.props.amount` and calling `fetchData()` instead of doing it only once on `componentDidMount`. – giotskhada Mar 06 '20 at 15:33
  • I change one line ``result: (state.rates[ownProps.convertTo] * ownProps.amount).toFixed(4), `` to ``result: (state.result[state.convertTo] * state.amount).toFixed(4), `` and now i have error : "cannot read property 'PHP' of null" – Daniel Gola Mar 06 '20 at 15:51

0 Answers0