the bellow component is for testing how to update a set with useState. The error occurs at state.has(num) The state variable from useState is a set and has is a set build-in function. Why this error happens?
import { useState } from "react";
function App() {
const [state, setState] = useState(new Set());
console.log(typeof state);
function clickHandler(num) {
if (!state.has(num)) {
setState(prevState => {
return setState(new Set(prevState).add(num))
})
} else {
setState((prevState) => {
return setState(new Set(prevState).delete(num));
});
}
}
return (
<>
<button onClick={() => clickHandler(1)}>1</button>
<button onClick={() => clickHandler(2)}>2</button>
<button onClick={() => clickHandler(3)}>3</button>
{ state}
</>
);
}
export default App;
CodePudding user response:
setState
returns undefined
Remove setState
from callback of setState
function clickHandler(num) {
if (!state.has(num)) {
setState(prevState => {
const set = new Set(prevState).add(num)
return set
})
} else {
setState((prevState) => {
const set = new Set(prevState).delete(num);
return set
});
}
}
CodePudding user response:
import { useState, useRef, useEffect } from "react";
function App() {
const [stateValue, setStateValue] = useState(0);
const previousValue = useRef(null);
console.log(typeof stateValue);
useEffect(() => {
previousValue.current = stateValue;
}, [stateValue]);
function clickHandler(num) {
setStateValue(num);
}
return (
<>
<button onClick={() => clickHandler(1)}>1</button>
<button onClick={() => clickHandler(2)}>2</button>
<button onClick={() => clickHandler(3)}>3</button>
<br />
<h5>number: {stateValue}</h5>
<h5>previous number: {previousValue.current}</h5>
</>
);
}
export default App;
best of luck :)