I created a calculator in react. Now I would like to use the global instead of the local state - I know that this solution may not have a larger session, but I want to learn redux in this way. I prepared the action and the reducer. I don’t know how to pass the values - I get an error with a non-existent result variable.
Link to application with local status:
Link to application with redux:
Code: index.js
Blockquote
import React from "react";
import { render } from "react-dom";
import { createStore } from "redux";
import { Provider } from "react-redux";
import App from "./components/App";
import calculate from "./reducers";
const store = createStore(calculate);
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
reducer - index.js
Blockquote
const calculate = (state, action) => {
switch (action.type) {
case "ADD_TO_MEMORY":
result += id;
return result;
case "ADD":
result = parseFloat(result) + parseFloat(prev);
return result;
default:
return result;
}
};
export default calculate;
action - index.js
Blockquote
let prev = "";
let result = "";
let current = "";
let disabled = true;
export const addToMemory = id => ({
type: "ADD_TO_MEMORY",
result: result
});
export const add = result => ({
type: "ADD",
result: result
});
App.js
Blockquote
let prev = "";
let result = "";
let current = "";
let disabled = true;
export const addToMemory = id => ({
type: "ADD_TO_MEMORY",
result: result
});
export const add = result => ({
type: "ADD",
result: result
});
Counter.js
Blockquote
import React from "react";
import { connect } from "react-redux";
import { addToMemory, add } from "../actions/index";
const Counter = ({ dispatch, result }) => {
return (
<p>
<button id="1" onClick={addToMemory("1")}>
1
</button>
<button id="1" onClick={addToMemory("2")}>
2
</button>
<button id="1" onClick={addToMemory("3")}>
3
</button>
<button id="1" onClick={addToMemory("4")}>
4
</button>
<button id="1" onClick={addToMemory("5")}>
5
</button>
<button id="1" onClick={addToMemory("6")}>
6
</button>
<button id="1" onClick={addToMemory("7")}>
7
</button>
<button id="1" onClick={addToMemory("8")}>
8
</button>
<button id="1" onClick={addToMemory("9")}>
9
</button>
<button id="1" onClick={addToMemory("0")}>
0
</button>
<p>RESULT: {result}</p>
</p>
);
};
export default connect()(Counter);