Hi, I am following the beginner redux counter tutorial, and had followed the steps - but my applications state is seemingly not updating. To be more clear, essentially the application is a counter with an increment button and a decrement button and it displays the current value on the screen.
I can get it to console log the value as it changes, but it doesn't output it on the screen. Can anyone tell me what I'm doing wrong
import React, { Component } from 'react';
import { createStore } from 'redux';
const counter = (state = 0, action) => {
switch(action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state -1;
default:
return state;
}
}
const store = createStore(counter);
store.subscribe(()=>{
console.log(store.getState());
});
class App extends Component {
render() {
return (
<div className="App">
<h1>Counter Application</h1>
<hr/>
<Counter
value={store.getState()}
onIncrement={() => store.dispatch({type: 'INCREMENT'})}
onDecrement={() => store.dispatch({type: 'DECREMENT'})}
/>
</div>
);
}
}
const Counter = ({
value,
onIncrement,
onDecrement
}) => {
return(
<div>
<h1>{value}</h1>
<button onClick={onIncrement}> Plus </button>
<button onClick={onDecrement}> Minus </button>
</div>
)
}
export default App;
Quentin
Traveller, coder and space enthusiast.
You haven't connect ed your redux store, to the react app.
The answer is that your component doesn't have a listener to be notified of an update. What you need to understand is that react updates components in 2 situations :
Your component `App` right now neither update the store or receive different props.
Here is what is happening to your application right now :
You actually got close to the answer by calling `store.subscribe` ! I suggest you think a bit more by calling it into your component `App`, and do some stuff there and see if you can find out a way to notify `App` that your store has changed, so it need to re-render.
I also suggest you, once you're familiar with that design pattern to take a look at react-redux, which is the way most people bind their Redux store to their react application right now. It'll basically do all the work you need to do right now for you !
Keep up !