Problems with 'Random Quote Machine'

I have some problems with it rigth now:

  1. ReactDOM doesn’t render my Redux React Wrapper.
  2. If I just render QuoteBox in ReactDOM, store isn’t sent with mapStateToProps() function as props.

It seems like I don’t completely understand how React and Redux work.

Here is my unfinished solution in CodePen:

OK, backing up a little bit, when I look in the console, I see this error:

TypeError: Cannot read properties of undefined (reading ‘quotes’)
at Function.mapStateToProps [as mapToProps] (pen.js:101:17)

When I look at that mstp, I see this:

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

First of all, that is not how you return an object from an arrow function with an implicit return. Remember that for objects it is a special case and you need to wrap it in parentheses:

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

But your issue is what state is. That message is saying “you are trying to accessed a property names ‘quotes’ on a something that is undefined”. That throws an error. Only reference types can have properties. (But JS has ways to handle then for primitives except for null or undefined - those throw errors.) So, figure out what that is:

const mapStateToProps = (state) => {
  console.log('state', state)
  return {
    quotes: state.quotes
  };
}

So my next idea would be to look at the reducer:

const quoteReducer = (state, action) => {
  console.log('quoteReducer', state)
	switch(action.type) {
		case ADD:
			return {
				quotes: [
					...state.quotes, 
					new Quote(action.text, action.author, action.color)
				]
			}
		default: 
			return state;
	}
}

What do you get there? Why? Did you forget something in your parameter list, something that sets up the reducer?

Oh, thanks. There were too many silly mistakes. And I forgot about state default value… Now it works properly. Thank you!!!

1 Like