I'm practicing playing with fixing/filtering poorly formatted JSONs and running into an annoying issue with displaying the resolved data.
Essentially, it should re-render after pressing the Clean button and show the updated values. The console.logs show the correct/updated data, but the re-render does not occur.
I feel like I'm just tired and not seeing something silly or forgetting something about async here. Suggestions would be great!
function App() {
const [uglyData, setUglyData] = useState(_uglyData);
const keyCleaner = async (arr) => {
const newData = await cleanupUndefinedKeys(arr);
// console.log(newData);
setUglyData(newData);
return newData;
}
return (
<Fragment>
<h1>List of Users</h1>
<div>
{uglyData.map((user) => {
return <User key={user.id} user={user} />;
})}
{/* <User user={uglyData[0]} /> */}
</div>
<div>
<button onClick={() => keyCleaner([...uglyData])}>
Clean undefined and empty string values
</button>
</div>
</Fragment>
);
}
export default App;
export const cleanupUndefinedKeys = async (arr) => {
const returnArr = [];
for(let i = 0; i < arr.length; i++) {
for(let key in arr[i]) {
if((key === 'email' || key === 'username' || key === 'roles') && (arr[i][key] === 'undefined' || arr[i][key] === '')) {
if(key !== 'roles') {
arr[i][key] = null;
} else arr[i][key] = [];
} else if(key === 'profile' && (arr[i][key] === 'undefined' || arr[i][key] === '')) {
for(let profileKey in arr[i][key]) {
if((profileKey === 'name' || profileKey === 'about' || profileKey === 'dob' || profileKey === 'address' || profileKey === 'company') && (arr[i][key][profileKey] === undefined || arr[i][key][profileKey] === '')) {
arr[i][key][profileKey] = null;
}
}
}
}
returnArr.push(arr[i]);
};
return returnArr;
}