Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140817

react redux awaiting state change so i can map

$
0
0

I'm trying Redux for the first time where I've been previously using React and its component state system. My code below works 100% in its vanilla react component state but its not working as it should with Redux. Fortunately I know the nature of the problem but don't know how to fix it. When I comment out my 'Spinner' which is my loading gif, redux updates the state and the action is executed. My asynchronus api call is made and the payload is retrieved. But when the 'Spinner' is not commented out, its throws a type error and Cannot read property 'map' of undefined. My reducer has an empty array as its initial state and im sure everything is set up properly but maybe its my component code.

class Votes extends Component {


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



  render() {
    const {error, isLoaded, foods} = this.props; 
    if (error) {
      return <div>Error : {error.message}</div>;
    // } else if (!isLoaded) {
    //   return <Spinner />;
    } else {
      return (
        <div>
          <h2>Menu</h2>
                    <ul>
                {foods.map(food=> (
                <li key={food._id}>
                    <div className="description">
                            <h4>{food.foodname}</h4>
                    </div> 
                </li>

                ))}

            </ul>
        </div>
      );
    }
  }
}

const mapStateToProps = state => ({
  foodReducer: state.foodReducer.foods
});

export default connect(mapStateToProps, {getfoods})(FoodComponent);

heres my initalState from my reducer file:

const initialState = {
   error: null,
   isLoaded: false,
   foods: [],
}

I don't think I need to provide my actions, store or reducer as it works if spinner is commented out but if you need to see that code to decipher this problem, I can make a future edit. thanks.


Viewing all articles
Browse latest Browse all 140817

Latest Images

Trending Articles



Latest Images