0

I am new to redux,While performing below example i cant render the output as expected.

App.js

 import React from 'react';
    import { Provider } from 'react-redux';
    import store from './store';
    import CakeContainer from './CakeContainer'
    
    function App(props) {
      return (
        <Provider store={store}>
         <CakeContainer />
        </Provider>
      );
    }
    
    export default App;

store.js

import {createStore} from 'redux';

const initialState = {cake:10}
const cakeReducer = (state = initialState,action) =>{
    switch(action.type)
    {
        case 'BUY_CAKE':
        return {
            ...state,
            cake : 5,
        }
        default :return state
    }
}
const store=createStore(cakeReducer);

export default store;

CakeContainer.js

import React from 'react';
import { connect } from 'react-redux';

function CakeContainer(props) {
    return <div>
            {props.buycake}
            <h1>Store cakes:{props.cake}</h1>
            </div> ;
}
const mapStateToProps= state =>{
    return {
        cake: state.cake
    }
}
const mapDispatchToProps= dispatch =>{
    return {
        buycake: () => dispatch({type:'BUY_CAKE'} )
    }
}
export default connect(mapStateToProps,mapDispatchToProps) (CakeContainer);

Console display warning as below : Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.

Can anyone please help me why buycake() is not rendered here and the output is cake:10 always in stead of cake:5.

1
  • use case "BUY_CAKE": not this case 'BUY_CAKE': Commented Aug 15, 2020 at 11:25

1 Answer 1

1
{props.buycake}

This line is trying to render a function onto the screen. That's not possible, and is causing the error you see. Presumably, you want to call the function, but i'm not sure when. Supposing you want to do it when a button is clicked, it might look like this:

function CakeContainer(props) {
  return (
    <div>
      <button onClick={props.buycake}>Click Me</button>
      <h1>Store cakes:{props.cake}</h1>
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ...It worked i thought it would call {props.buyCake} during page loads.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.