I am facing the current issue. Whenever I click on the button +
the onChange
event is late on the last input when i try to save that value to the localStorage
I am new to using redux
with react hooks
How can I possibly fix this?
const ADD_BIRD = 'ADD_BIRD';
const INCREMENT_BIRD = 'INCREMENT_BIRD';
export function addBird(bird) {
return {
type: ADD_BIRD,
bird,
}
}
export function incrementBird(bird) {
return {
type: INCREMENT_BIRD,
bird
}
}
let defaultBirds = [];
if (window.localStorage.getItem('bird') !== null) {
defaultBirds.push(
{
name: 'robin',
// get localStorage value as number
views: parseInt(window.localStorage.getItem('bird')),
}
);
} else {
defaultBirds.push(
{
name: 'robin',
views: 1,
}
);
}
function birds(state=defaultBirds, action) {
switch (action.type) {
case ADD_BIRD:
return [
...state,
{
name: action.bird,
views: 1
}
];
case INCREMENT_BIRD:
const bird = state.find(b => action.bird === b.name);
const birds = state.filter(b => action.bird !== b.name);
console.log("birds", typeof(bird.views));
// save to localStorage
window.localStorage.setItem('bird', bird.views);
return [
...birds,
{
...bird,
views: bird.views + 1
}
];
default:
return state;
}
}
function App() {
const [birdName, setBird] = useState('');
const birds = useSelector(state => state.birds);
const dispatch = useDispatch();
const handleSubmit = event => {
event.preventDefault();
dispatch(...addBird(birdName), setBird())
setBird('');
};
useEffect(() => {
}, [birdName])
return (
<div className="wrapper">
<h1>Bird List</h1>
<form onSubmit={handleSubmit}>
<label>
<p>
Add Bird
</p>
<input
type="text"
onChange={e => setBird(e.target.value)}
value={birdName}
/>
</label>
<div>
<button type="submit">Add</button>
</div>
</form>
<ul>
{birds.map(bird => (
<li key={bird.name}>
<h3>{bird.name}</h3>
<div>
Views: {bird.views}
<button
onClick={() => dispatch(incrementBird(bird.name))}>
<span role="img" aria-label="add">
➕ # + SIGN IS HERE
</span></button>
</div>
</li>
))}
</ul>
</div>
);
}
export default App;
Looking forward to some help.
You are setting window.localStorage.setItem('bird', bird.views), whereas you actually want the updated views (bird.views + 1).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.