This is how experienced developers cleanse data in React

John Mwakalinga
We Code & We Write
Published in
2 min readNov 7, 2022

The best way to sanitize data in your React applications

Today’s ReactJS applications all involve data in some form. Throughout the entire program, we are fetching data and enabling user interaction.

However, if we are not vigilant about the data that enters our website, it may result in the failure of our application.

We’ll look at one method for sanitizing data in React applications today.

What are we trying to solve?

Never put your confidence in anyone. You could have anticipated receiving this kind of data from a remote API.

postData = {
metadata: {
type: string;
length: number;
}
}

And you have a component that displays these two pieces of information in the manner shown below.‌

export const PostComponent = ( {postData} ) => {
return (
<div>
<div> {postData.metadata.length ?? ""}
</div>
)
}

For whatever reason, the backend developer decided to tweak the data’s structure a bit to make it flatter and change it to‌

postData = {
type: string;
length: number;
}‌

Your program will now crash at runtime because it won’t be aware that the structure has changed as soon as they do that.

Your users will be met with a crashed application while you are away from your workstation fixing the problem.‌

Error: Cant't read name of undefined

In order to prevent a collision, you can try something like this,

<div> {post?.metadata?.length} </div>

The experienced developer’s solution

Let’s now define our Post model as follows:

interface Post {
type: string;
length: number;
}
function initializePost(options?: Partial<Post>): Post {
const presetOptions = {
type: '',
length: 0;
};
return {
...presetOptions,
...options,
};
}
const p1: Post = initializePost();
console.log(p1); // -> {type: '', length: 0}
const p2: Post = initializePost({ type: 'React'});
console.log(p2); // -> {type: 'React', age: 0}

Read the rest of the article at Quid Experience to support the creator 😊💪🏽

--

--

We Code & We Write
We Code & We Write

Published in We Code & We Write

Tell me and I forget. Teach me and I remember. Code with me and I learn.

John Mwakalinga
John Mwakalinga

Written by John Mwakalinga

Developer. A bit biased to Laravel, JS and TS. I write about software and life topics. 🇹🇿. Checkout https://whenprogramming.com