I am creating a pluggable widget for Mendix and am having some trouble using useState. I am trying to initialize useState using a function to create and return Array of Objects. Despite the function working as intended, my useState never get's updated and always remains as an empty array.
This is my code:
const [data, setData] = useState<Data[]>(getData);
function getData() {
let dataArray: Data[] = [];
props.data.items?.map((item) => {
dataArray.push({
id: props.id.get(item).value?.toNumber(),
Name: props.name.get(item).value?.toString(),
Status: props.status.get(item).value?.toString(),
clicked: false,
})
})
return dataArray;
}
I am using TypeScript, and have created a type interface for my useState:
export interface Data {
id?: Big | number,
Name?: string;
Status? : string;
clicked : boolean;
LinkedData?: [
{
id: Big;
Name : string,
Status? : string
}
]
}
I am not getting any errors in my files, nor in my console, but useState never gets updated. The data being accessed within the function is data passed to the widget.
What could I be doing wrong?
I would initialize the state with an empty array and then, in a useEffect set the actual data. As the dependency array you can use
[props.data.items, props.id, props.name, props.status].That way, when the data becomes available, the state will be (re)set.
Also, I would change this:
To:
And then set the state to
updatedData. You are usingmapafter all... otherwise you could just as well do aforEach(which is less elegant here).Also, you can add a guard clause in your
useEffectto only update when everything is available.