Ray Jiang
Ray Jiang

Reputation: 35

redux store not getting updated and component not rerenders

I have a question regarding of using redux.

  1. My initial state for text in my store never gets initialize and always return undefined
  2. component did not re render from state changes

function App(props) {
  useEffect(() => {
    console.log(props);
  }, [props]);
  return (
    <div className="App">
      <h1>{props.text && props.text}</h1>
      <button onClick={() => props.setText()}>change</button>
    </div>
  );
}

const mapStateToProps = state => {
  return {
    text: state.text
  };
};

const mapDispatchToProps = dispatch => ({
  setText: () => dispatch(setCurrentText())
});

export default connect(mapStateToProps, mapDispatchToProps)(App);

reducer

const initial_state = {
  text: "hello"
};

export const textReducer = (state = initial_state, action) => {
  switch (action.type) {
    case "text-change":
      console.log("in here reducer", action);

      return { ...state, text: action.payload };
    default:
      return state;
  }
};

action

export const setCurrentText = () => {
  return {
    type: "text-change",
    payload: "change now"
  };
};

Upvotes: 0

Views: 33

Answers (1)

Kinjal
Kinjal

Reputation: 26

import {textReducer} from './reducer';

function App(props) {
  useEffect(() => {
    console.log(props);
  }, [props]);
  return (
    <div className="App">
      <h1>{props.text && props.text}</h1>
      <button onClick={() => props.setText()}>change</button>
    </div>
  );
}

const mapStateToProps = state => {
  return {
    text: state.textReducer.text
  };
};

const mapDispatchToProps = dispatch => ({
  setText: () => dispatch(setCurrentText())
});

export default connect(mapStateToProps, mapDispatchToProps)(App); 

Upvotes: 1

Related Questions