How To Parse CSV Files - React & TypeScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to the coding Loft my name is Samuel and in today's video you will learn how to power CSV files in your react project with typescript so if you have CSV data in your project and you want to use it as a JavaScript object this is the tutorial for you so as you can see in our case right here we have this large recipe database file that holds all of these different recipes and this is already the final output where we have pared the CSV to JavaScript and then display it in our Project without further Ado let's get started as you can see we have a very barebone setup right here it's just a bare bone app with a heading one and heading three and what we will focus on is the data right here in our root folder in this data folder we have a CSV file called recipe database which contains a lot of different information about recipes from an online cooking school now what we want inside of our app we want to use this as the main data to then Loop through the data and work with the different values that we get in this CSV file so we start by setting a state variable which is called Data in our case and a callback function called set data which can then change this data property and we will get it by calling the use State hook right here and when I click it it will automatically import our use State Hook from react at the top and since this is a typescript project we need to Define the types so we say that our data is an array by specifying an empty array right here and then we also want to specify the type the input type that we can have which in our case is an array that can contain data of any type in our case this will be an object now how do we parse this CSV data to be used as a JavaScript object or array for that there's a handy little library that you can install that is called Papa pars so you will need to run this command npmi Papa pars to install it in your project so I copy it to my clipo Port open the terminal and then install it inside of the project so now we can use it inside of our react project and now as the next step we want to create a reusable function that allows us to input any CSV file that we have in our project and convert it to a JavaScript object now for that we want to create a new use fetch hook and we will save it right here in our source folder in a new folder called Hooks and in here we will create a new file which is called use fetch. TSX and here we will create our use fetch hook so we say const fetch equals a callback function and at the end we want to export our use fetch hook now inside of here we want to create a function that allows us to fetch the data from the CSV file so I'll call this const fetch CSV data and this is an asynchronous function so we need to wait for the result to arrive and here inside of our use fetch function we always want to return an object with all of the different functions that we Define in here so in our case we want to return the fetch CSV data function so we can then later import it inside of our app now this fetch CSV data function will take in two arguments one is the file path so our case we want to tell the program where in our project it can find this CSV file and this file path is of type string so that's easy and then we want to run a callback function which in our case will be the set data function that we have in our app. typescript file and for this we also need to specify type which is the type callback that we Define in just a moment so up here we say type callback and we say callback is a function that returns nothing because it just sets a value and this callback function can have any data input type so now to recap this fetch CSV data function first first of all it wants to know the path where is our CSV file and then it wants to know a function what do we want to do with the CSV data that we get now first of all we want to get a response because we will use the fetch function and the fetch function is asynchronous so that's why we have an asynchronous function right here and we say whenever we wait what the fetch function returns we save it in this variable called response and we want to return whatever it gets from file path then we create a variable called reader and we get this from our response object from the body of it and in there we have a method called get reader so as you can see typescript complaints and the reason is that response. body is possibly null so in order to avoid that we can use the exclamation mark here which is the non-null assertion basically meaning that whenever our body is not null then we can call call the get reader method and then we get a result by saying we await whatever reader returns when we call the read method then we have a decoder variable which is basically a new instance of the text decoder class and in here we specify the type that we want to decode so in our case it's utf8 and last but not least we get our CSV string by saying decoder do decode and then it should decode result. value and again you can add the exclamation mark here to assert that this is not null now so far we have not used the papa pars Library that's what will happen next when we get a data object back from the papa pars Library so we need to say papa. pars but of course we first need to import it because as you can see it cannot find the name Papa yet we haven't imported this Library yet so up here we simply say import Papa from Papa pars and you see it complains that it doesn't find this module so we'll run this command npmi D- save-dev and then add types / Papa pars and now you can see we don't have this problem anymore but now it complaints down here because it says that it expects a couple of arguments so let's do that next so Papa pass wants two things first of all it wants the CSV file which in our case is the CSV string the second argument is an object with different options so header we say true header basically means that the first row in our CSV file is the name of the columns if it's set to false then it will treat the first row already like the other rows and then we have the dynamic typing option which we also set to true this will let papa parus infert the data inside of our CSV file so for instance whether it's a string or a number and then last but not least we want to call our callback function and pass this data array in here so to summarize we have a function called Fetch CSV data which takes two arguments which is the file path and a callback function the file path means where in our project it can find the CSV file the Callback function basically then allows us to use this data in different ways in our case we will use the set data function so we get a response by fetching the data from the file path we read the result results from the response object we and then we turn it into JavaScript data which we can then insert as an argument inside of our callback function so now inside of app typescript we can use this fetch CSV data method to fetch the data so first of all we need to import our use fetch function from hooks sluse Fetch and then we can get the fetch CSV data function from our use fetch hook so in our case we want to fetch this data the first time that we load our page so we use the use hook and again it Imports it up here in our object so now we can use it and the use effect hook takes in a callback function and at the end uh we specify an empty array meaning that it runs the first time that we load the page and in here we then want to call this fetch CSV data function that we defined so if you remember we first need to specify a file path which in our case is the root folder then we have a data folder in here and then we have a recipe data base. CSV file and then the second argument is the Callback function so in our case it's the set data function right here so in order to see that this is working we now can call our data and console. log it and now I can see that we have this array of objects and each object is a a recipe object that contains a lot of different information about the recipe so now to see that this is working we can then use the data array and we can map through it so that means that for each recipe that we have in here we can then return some HTML so in our case we can print the recipe name to the app so in our case we then call the recipe item and in there there is a property called recipe name and now it should be printed to the screen you can see all of the different recipe names right here now in the second part of this project I actually want to sanitize the names of our CSV file because you can see that they are always written with capital letters then sometimes they have space in between and sometimes a dash such as an image URL and instead I want to have everything in lowercase and with underscores in between and the reason is very simple because when I want to access the properties of the item I always have to use this bracket notation I cannot use the dot notations simply because there is this space in here so in order to do that let's jump back to our use fetch hook and right here we want to create a new function called sanitize columns which again is a function and it takes in data of any type so what we want to do is we want to again return data but we want to change each item and we use the map method to Loop through each item so in here we have an item of type any and then we run a callback function so in our case our data is an array consisting of object so we map through the entire array and we look at each recipe object which is then referred to as item and instead of this item we want to have a sanitized item that's what we then want to return to our data and in the beginning this is an empty object now what I want to do is I want to get all of the different names that we have right here all of the different keys of this object and the way you can get all of these Keys is by saying object. keys of the current item so this basically is an array that contains all of the different Keys now the good thing about an arrays we can Loop through it so we call it for each function and here we can work with each key so for instance in the first iteration it will go over category then over Chef then over common course number and so on so in this moment we can then use each key and transform it a little bit so we want to have a sanitized key and sanitized key is the current key and what do we want to do to sanitize it we want to call the dot to lower case method so now the key is all lowercase and now we want to replace a couple of things so we call the do replace method and in here we can specify ify what we want to replace as the first argument and the second you want to replace it and it can be if there's one or two spaces one or two slashes right after each other that's the plus sign right here we want to replace those and the g flag here stands for Global so this means that this should apply to all all of the instances that we find so for instance if there are several spaces between several words we want all of them to be replaced with this underscore here last but not least we want to now fill our sanitized item object and we want to append to it the key which is our sanitized key and then the value should be whatever is currently in item with the current key and you see that typescript complaints appear so when we Define the sanitized item object right here we need to tell it that it can have any types inside and last but not least we want to return this sanitized item now how do we use this function down here we want to create a new variable called stied data and we sanitize the data by saying sanitize columns and then we pass in the data that we got from our Papa parus method right here we pass it in here and instead of putting the data as the argument we want to to add in this sanitized data right here and now you can see it has sanitized the column names so all of them are now a lowercase and we have the underscores in between the words so no matter if there was a dash before or a space we now always have an underscore and that means that down here I could say recipe. recipe name for instance and now you can see that it allows us to access all of these properties by using this dot notation right here so that is how you can very simply par a CSV file in your react and typescript project and then work with it as a regular JavaScript object so in our case we get back an array that consists of different recipe objects if you did like this video please leave a like and a comment down below and don't forget to subscribe to the channel for more videos like this in the future also I would love to hear from you do you find this useful in what kind of project are you parsing CSV files and what other questions would you have about react and typescript thanks for watching see you in the next video [Music]
Info
Channel: The Coding Loft
Views: 1,668
Rating: undefined out of 5
Keywords: Web development, Frontend development, React, Python, HTML, CSS, JavaScript, Frameworks, Single-page Applications (SPA), Full-stack development, Object-oriented programming (OOP), Functional programming, Visual Studio Code, react, react typescript, react typescript tutorial, react typescript parse csv, react typescript how to parse csv files, react typescript parse csv to json, csv parser react, csv parser, how to parse csv files react, learn web development, web development tutorial
Id: 435HHLfR-c0
Channel Id: undefined
Length: 15min 14sec (914 seconds)
Published: Fri Oct 13 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.