I have the following piece of code and the usereducer disptach method is getting called twice. I read up on this and removed the strict mode from index. Now the method is called and run properly but the UI is not getting rendered with the updated value. Can someone please help?
import React, { useReducer, useState } from "react";
import "../App.css";
const initialState = [
{ time: "17:00", slots: 3 },
{ time: "18:00", slots: 4 },
{ time: "19:00", slots: 2 },
{ time: "20:00", slots: 4 },
{ time: "21:00", slots: 3 },
{ time: "22:00", slots: 2 },
];
const reducer = (state, action) => {
switch (action.type) {
case "update": {
let index = state.findIndex((x) => x.time === action.value);
console.log(index);
if (state[index].slots > 0) {
state[index].slots -= 1;
}
console.log(state);
return state;
}
}
};
function Reservations() {
const [availableTimes, dispatch] = useReducer(reducer, initialState);
const handleSubmit = (e) => {
e.preventDefault();
dispatch({ type: "update", value: time });
};
return (
<>
<label htmlFor="res-time">Choose time</label>
<select
id="res-time "
value={time}
onChange={(e) => setTime(e.target.value)}
>
{availableTimes.map((availableTime) => {
return (
<option key={availableTime.time} value={availableTime.time}>
{availableTime.time} - {availableTime.slots} slots available
</option>
);
})}
</select>
</>
);
}
export default Reservations;
In my index.js, I have removed the strictmode
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { BrowserRouter } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
// <React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
// </React.StrictMode>
);
React expects immutable updates. Do not directly change the state by assigning to it; instead make copies to represent the next state.
return state.map(x => x.time !== action.value ? x :
{...x, slots: Math.max(0, x.slots - 1)});