I am just started using redux in my react app and I have successfully added some values on my redux store.On the same component where dispatching happens I can access the store via
store.getState();
but on other components I can't access it by mapStateToProps or the above method. I really need to why this happens.
index.js
const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider store={store} > <App /> </Provider>, rootElement);
store.js
import { createStore } from "redux";
import rootReducer from "../reducers/index";
const store = createStore(rootReducer);
export default store;
reducer.js
const initialState = {
token:"",email:"",uid:""
};
function userReducer(state = initialState, action) {
console.log("check ", state, action);
switch(action.type) {
case "ADD_USER":
return Object.assign({}, state, {
token : action.token,
email : action.email,
uid : action.uid
});
default : return state;
}
}
export default userReducer;
action.js
const addUser = (token,email,uid) => ({
type:"ADD_USER",token:token,email : email,uid:uid
})
export default addUser;
login.js
function mapDispatchToProps (dispatch) {
console.log(dispatch);
return { addUser : (token,email,uid)=> dispatch(addUser(token,email,uid))
};}
class Sample extends React.Component {
constructor(props){
super(props);
this.state = {...........}
}
componentDidMount() {
let token = localStorage.getItem("myToken");
let user = decode(token);
let uid = user.id;
let email = user.email;
this.props.addUser(token,email,uid);
console.log(this.props.state);
console.log(store.getState());
}
}
const mapStateToProps = state => {
return {state:state}
}
export default connect(mapStateToProps,mapDispatchToProps)(Sample);
anotherPage.js
export default function AnPage() {
const Data = useSelector(state=>state.userReducer);
useEffect(()=> {
somFunct(); },[]);
}
someFunct=() => {
console.log(Data) =>output is ({token: "", email: "", uid: ""})
return(
)
}
console output at reducer.js
check {token: "", email: "", uid: ""}token: ""email: ""uid: ""__proto__: Object {type: "ADD_USER",
token: "*******", email: "dfgsdhf@gmail.com", uid: 6264}
console.log(this.props.state)->
userReducer: {token: "", email: "", uid: ""}
__proto__: Object
console.log(store.getState()) ->
userReducer: {token: "*******", email: "dfgsdhf@gmail.com", uid: 6234}
__proto__: Object
I have edited the question.