Search code examples
asynchronousreact-nativestorereducersaxios

React-Native Not Merging Props After ComponentDidUpdate call to Async


I am working on learning how to set up async api calls in react-native. I am using axios. I am sending a dispatch on ComponentDidMount that is successfully changing/updating my general state. The problem is that I can't seem to use this "data."

import React, { Component, PropTypes } from 'react'
import { StyleSheet, View, Text, TouchableOpacity } from 'react-native'
import { connect } from 'react-redux'
import { getMakes} from "../actions/getPrice"
import * as PriceActions from '../actions/getPrice'


@connect((store) => {
  return {
    cars: store.cars
  };
})
export default class CounterContainer extends Component {

  constructor(props) {
    super(props);
    this.state = {
        cars: {

        }
    }
  }

  componentDidMount() {
    this.props.dispatch(getMakes())
  }


  render() {
    return (
      <View style={styles.container}>

        <TouchableOpacity>
          <Text style={styles.back}>Data: {this.props.cars.modelsCount}</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

Since the action is working correctly, it must be a problem with my reducer? It stands as follows:

function getPrice(state={
    cars: [],
    fetching: false,
    fetched: false,
    error: null,
  }, action) {
    switch (action.type) {
      case "FETCH_CARS": {
        return {...state, fetching: true}
      }
      case "FETCH_CARS_REJECTED": {
        return {...state, fetching: false, error: action.payload}
      }
      case "FETCH_CARS_FULFILLED": {
        return {
          ...state,
          fetching: false,
          fetched: true,
          cars: action.payload,
        }
      } 
    }
    return state
}

export default getPrice;

enter image description here


Solution

  • mapStateToProps takes whole state tree as first argument. If state on screenshots is your full redux state, then connecto should look like this:

    @connect((store) => {
      return {
        cars: store.priceReducer.cars
      };
    })