I am just trying to figure out how to use prevState in the useState hook with React typescript. The button are mapped using the data from the objectData.
So far I have:
let data = dataFromFile;
const [chart, setChart] = React.useState<ChartInterface[]>(data);
in the component I am doing:
export interface ActiveObject {
id: number;
title: string;
cb: (idx: number) => void;
};
export interface ButtonGroupState {
activeObject: ActiveObject | null;
objects: ActiveObject[];
};
export interface ButtonGroupProps {
data: Array<ActiveObject>
}
const ObjectData: ActiveObject[] = [
{
id: 1,
title: "1 way day",
cb: () => { setChart(prevState => prevState.set(Data7Day)) }
},
];
But that does not really work, any idea's? I get Property 'set' does not exist on type 'ChartInterface[]'. I know thats to do with the interface, but is that the way to do use PrevState in useState and is it needed at all?
According to the docs:
If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value. Here’s an example of a counter component that uses both forms of setState:
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
</>
);
}
So, basically what that means is that you can also pass a function to the setter function returned by the useState Hook.
You need to pass the argument as function, when you need to set the next state, on basis of the current one. As @RameshReddy pointed, if cb function should just change the chart array to a new array called Data7Day, you don't need to use a functional state update, you can directly call setChart(Data7Day)
for ex...
const [count, setCount] = useState(0);