DEV Community

Mohammad Faisal
Mohammad Faisal

Posted on • Edited on • Originally published at Medium

3

How to Sanitize Data in React

To read more articles like this, visit my blog

Every modern ReactJS application deals with data in some way. We are fetching data and letting people interact with it throughout the whole application.

But if we are not careful about what data is coming into our website it can cause our application to fail.

One of the major reasons an application crashes on runtime is bad data.

Today we will see one way to sanitize data in React applications.

The problem

You should never trust anyone. Maybe you are expecting a remote API to return a piece of data that looks like this.

userData = {
  basicInfo: {
    name: string;
    age: number;
  }
}
Enter fullscreen mode Exit fullscreen mode

And you have a component that shows these two piece of data in the following manner.

export const SomeComponent = ( {userData} ) => {
return (
    <div>
      <div> {userData.basicInfo.name ?? ""}
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Now for some reason, the developer of the backend thought, okay, let’s change the structure of the data a bit to make it flatter and change it to

userData = {
  name: string;
  age: number;
}
Enter fullscreen mode Exit fullscreen mode

Now, as soon as they do that, your application will fail on runtime because it doesn’t know that the structure was changed.

You will return to the desk and fix the issue, but your users will be greeted with a crashed application the whole time.

Error: Cant't read name of undefined
Enter fullscreen mode Exit fullscreen mode

One way to avoid a crash like this is

<div> {user?.basicInfo?.name} </div>
Enter fullscreen mode Exit fullscreen mode

But you have to put these ? sign everywhere which is not so clean, right?

Take advantage of Typescript.

Now let’s define our User model like the following

interface User {
  name: string;
  age: number;
}

function initUser(options?: Partial<User>): User {
  const defaults = {
    name: '',
    age: 0;
  };
return {
    ...defaults,
    ...options,
  };
}

const p1: User = initPerson();
console.log(p1); // -> {name: '', age: 0}

const p2: User = initPerson({ name: 'Tom'});
console.log(p2); // ->  {name: 'Tom', age: 0}
Enter fullscreen mode Exit fullscreen mode

So this initUser method can be used to create an instance of User, and the options parameter makes it easy to pass parameters if we want.

If we don’t pass anything, we will get back the object with default values.

So before you push the data into the component, you will pass it via the initUser method and stay chilled.

Or you can use a hook.

const useCleanUserData = (userData: User) => {
   return initUser(userData);
}


// inside component
const cleanUserData = useCleanUserData(userData);
Enter fullscreen mode Exit fullscreen mode

This way, we don’t need to worry about whether the API data is clean or not.

You can use this same approach for redux as well. take advantage of the selectors so that the data is cleaned before they enter into the component.

Have something to say? Get in touch with me via LinkedIn or Personal Website

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
masekere profile image
Gift Masekere

I never thought of the importance of sanitizing data. Well, being concerned about the code working at the moment and not being concerned about the future, seems to be increasing more bugs. Thanks man for sharing 🤝

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay