Category: JavaScript

How to Work with the Latest JS features in React

Working with the latest javascript features in React

React is mainly written with modern JavaScript (ES6, ES7, and ES8). If you want to take advantage of React, there are some modern JS features that you should master to get the best results for your React applications.

In this article, you’ll learn the essential JS features so that you are ready to start working on your first React application.

How to do it

In this section, you’ll see how to use the most important JS features in React:

  • let and const: The new way to declare variables in JavaScript is using let or const. You can use let to declare variables that can change their value but in a block scope. The difference between let and var is that let is a block scoped variable that cannot be global, and with var, you can declare a global variable, for example:

  • The best way to understand block scope is by declaring a forloop with var and let. First, use var and see its behavior:

  • If you write the same code with let, this will be the result:

  • With const, you can declare constants, which means that the value can’t be changed (except for arrays and objects):

  • If you declare an array with const, you can manipulate the array elements (add, remove, or modify elements):

  • Also, using objects, you can add, remove, or modify the nodes:

  • Spread operator:The spread operator (…) splits an iterable object into individual values. In React, it can be used to push values into another array, for example when you want to add a new item to a to-do list utilizing setState:

  • Also, the Spread operator can be used in React to spread attributes (props) in JSX:

  • Rest parameter:The rest parameter is also represented by …. The last parameter in a function prefixed with … is called the rest parameter. The rest parameter is an array that will contain the rest of the parameters of a function when the number of arguments exceeds the number of named parameters:

  • Destructuring: The destructuring assignment javascript feature is the most used feature in React. It is an expression that allows you to assign the values or properties of an iterable object to variables. Generally, with this, you can convert your component props into variables (or constants):   

  • Arrow functions: In Javascript ES6 provides a new way to create functions using the => These functions are called arrow functions. This new method has a shorter syntax, and the arrow functions are anonymous functions. In React, arrow functions are used as a way to bind the this object in your methods instead of binding it in the constructor:

  • Template literals: The template literal is a new way to create a string using backticks ( ) instead of single quotes (‘ ‘)   or double quotes (” “). React uses template literals to concatenate class names or render a string using a ternary operator:
  • Map: The map()method returns a new array with the results of calling a provided function on each element in the calling array. Map use is widespread in React and mainly used to render multiple elements inside a React component.For example, it can be used to render a list of tasks:

  • assign(): The Object.assign()method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object. This method is used mainly with Redux to create immutable objects and return a new state to the reducers:

  • Classes: JavaScript classes, introduced in ES6, are mainly a new syntax for the existing prototype-based inheritance. Classes are functions and are not hoisted. React uses classes to create class Components:

  • Static methods: Static methods are not called on instances of the class. Instead, they’re called on the class itself. These are often utility functions, such as functions to create or clone objects. In React, they can be used to define the PropTypes in a component:

  • Promises:The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Use promises in React to handle requests using axios or fetch; also, you can use Promises to implement server-side rendering.
  • async/await: The async function declaration defines an asynchronous function, which returns an AsyncFunction This can also be used to perform a server request, for example, using axios:

If you found this article interesting, you can explore React Cookbook, which covers UI development, animations, component architecture, routing, databases, testing, and debugging with React. React Cookbook will save you from a lot of trial and error and developmental headaches, and you’ll be on the road to becoming a React expert.

Creating Queues for In-Order Executions With JavaScript by using WeakMap()

A queue is a programming construct that bears a heavy resemblance to real-world queues, for example, a queue at the movie theater, ATMs, or the bank. Queues, as opposed to stacks, are first-in-first-out (FIFO), so whatever goes in first comes out first as well. This is especially helpful when you would like to maintain data in the same sequence in which it flows.

Types of queues

Before you understand queues, take a quick look at the types of queues that you may want to use in your applications:

  • Simple queue: In a simple FIFO queue, the order is retained and the data leaves in the same order in which it comes in
  • Priority queue: A queue in which the elements are given a predefined priority
  • Circular queue: Similar to a simple queue, except that the back of the queue is followed by the front of the queue
  • Double ended queue(Dequeue): Similar to the simple queue but can add or remove elements from either the front or the back of the queue

Implementing APIs

Implementing an API is never as easy as it seems. When making generic classes, you can never predict what kind of situation your queue is going to be used in. Some of the most common operations that you can add to the queue are as follows:

  • add(): Pushes an item to the back of the queue
  • remove(): Removes an item from the start of the queue
  • peek(): Shows the last item added to the queue
  • front(): Returns the item at the front of the queue
  • clear(): Empties the queue
  • size(): Gets the current size of the queue

Creating a queue

Of the four types of queues discussed earlier, this article will teach you to implement a simple and priority queue.

A simple queue

To create a queue, use the following steps:

  1. Define a constructor():

  1. Use WeakMap()for in-memory data storage:

  1. Implement the methods described previously in the API:

You need to wrap the entire class inside an IIFE because you don’t want to make Queue items accessible from the outside:

Testing a simple queue

To test this queue, you can simply instantiate it and add/remove some items to/from the queue:

As you can see in above code, all the elements are treated the same. Irrespective of the data they contain, elements are always treated in a FIFO fashion. Although that is a good approach, sometimes you may need something more: the ability to prioritize elements that are coming in and leaving the queue.

Priority Queue

A priority queue is operationally similar to a simple queue, that is, they support the same API, but there is a small addition to the data they hold. Along with the element (your data), they can also persist a priority, which is just a numerical value indicating the priority of your element in the queue.

Addition or removal of these elements from the queue is based on priority. You can either have a minimum priority queue or a maximum priority queue, to help establish whether you are adding elements based on increasing priority or decreasing priority. Now let’s see how we can use the add() method in the simple queue:

Since you are accounting for the priority of the elements while they are being inserted into the stack, you do not have to concern yourself with priority while you remove elements from the queue. So, the remove() method is the same for both simple and priority queues. Other utility methods, such as front(), clear(), peek(), and size(), have no correlation with the type of data that is being saved in the queue, so they remain unchanged as well.

A smart move while creating a priority queue would be to optimize your code and decide whether you would like to determine the priority at the time of addition or removal. That way, you are not over calculating or analyzing your dataset at each step.

Testing a priority queue

First set up the data for testing the queue:

Visually, the preceding steps would generate a queue that looks as follows:

Note how when you add an element with a priority 2 it gets placed ahead of all the elements with priority 1:

And when you add an element with priority 1 (lowest), it gets added to the end of the queue:

In the above image, by adding the last element apply the lowest priority in the order, which makes it the last element of the queue, thus keeping all the elements ordered based on priority.

Now, remove the elements from the queue:

There you have it: the creation of simple and priority queue in JavaScript using WeakMap().

If you found this article interesting, you can explore Kashyap Mukkamala’s Hands-On Data Structures and Algorithms with JavaScript to increase your productivity by implementing complex data structures and algorithms. This book will help you gain the skills and expertise necessary to create and employ various data structures in a way that is demanded by your project or use case.

Building the KNN algorithm With JavaScript

k-Nearest Neighbor (KNN)

The KNN is a simple, fast, and straightforward classification algorithm. It is very useful for categorized numerical datasets, where the data is naturally clustered. It will feel similar in some ways to the k-means clustering algorithm; with the major distinction being that k-means is an unsupervised algorithm while KNN is a supervised learning algorithm.

If you wish to perform a KNN analysis manually, here’s how it should go: first, plot all your training data on a graph and label each point with its category or label. When you wish to classify a new, unknown point, put it on the graph and find the k closest points to it (the nearest neighbors).

The number k should be an odd number in order to avoid ties; three is a good starting point, but some applications will need more and some can get away with one. Report whatever the majority of the k nearest neighbors is classified, as that will be the result of the algorithm.

Finding the k nearest neighbors to a test point is straightforward, but you can use some optimizations if your training data is very large. Typically, when evaluating a new point, you would calculate the Euclidean distance (the typical, high school geometry distance measure) between your test point and every other training point, and sort them by distance. This algorithm is quite fast because the training data is generally not more than 10,000 points or so.

If you have many training examples (in the order of millions) or you really need the algorithm to be lightning-fast, there are two optimizations you can make. The first is to skip the square root operation in the distance measure and use the squared distance instead. While modern CPUs are very fast, the square root operation is still much slower than multiplication and addition, so you can save a few milliseconds by avoiding the square root.

The second optimization is to only consider points within some bounding rectangle of distance to your test point; for instance, only consider points within +/- 5 units in each dimension from the test point’s location. If your training data is dense, this optimization will not affect the results but will speed up the algorithm because it will avoid calculating distances for many points.

The following is the KNN algorithm as a high-level description:

  • Record all training data and their labels
  • Given a new point to evaluate, generate a list of its distances to all training points
  • Sort the list of distances in the order of closest to farthest
  • Throw out all but the knearest distances
  • Determine which label represents the majority of your knearest neighbors; this is the result of the algorithm

A more efficient version avoids maintaining a large list of distances that need to be sorted by limiting the list of distances to k items. Now get started with your implementation of the KNN algorithm.

Building the KNN algorithm

Since the KNN algorithm is quite simple, you can build your own implementation:

  1. Create a new folder and name it Ch5-knn.
  2. Add the following jsonfile to the folder. Here, you have added a dependency for the jimp library, which is an image processing library:

  1. Run the yarn installcommand to download and install all the dependencies and then create subfolders called src, dist, and files.
  2. Inside the srcfolder, create an js file and a knn.js file.

You will also need a data.js file. For these examples, a larger dataset has been used which is difficult to be printed here, so you should take a minute to download the Ch5-knn/src/data.js file from GitHub. You can also find the complete code for this article at https://github.com/PacktPublishing/Hands-On-Machine-Learning-with-JavaScript/tree/master/Chapter05/Ch5-knn.

  1. Start with the jsfile. You’ll need a distance-measuring function. Add the following to the beginning of knn.js:

If you really need a performance optimization for your KNN implementation, this is where you might omit the Math.sqrt operation and return just the squared distance. However, since this is such a fast algorithm by nature, you need to do this only if you’re working on an extreme problem with a lot of data or with very strict speed requirements.

  1. Next, add the stub of your KNN class. Add the following to js, beneath the distance function:

The constructor accepts three arguments: the k or the number of neighbors to consider when classifying your new point, the training data split up into the data points alone, and a corresponding array of their labels.

  1. Next, you need to add an internal method that considers a test point and calculates a sorted list of distances from the test point to the training points. You can call this a distance map. Add the following to the body of the KNN class:

This method could be easier to read, but the simpler version is not efficient for very large training sets. What you’re doing here is maintaining a list of points that might be the KNNs and storing them in map.

By maintaining a variable called maxDistanceInMap, you can loop over every training point and make a simple comparison to see whether the point should be added to your candidates’ list. If the point you’re iterating over is closer than the farthest of your candidates, you can add the point to the list, re-sort the list, remove the farthest point to keep the list small, and then update mapDistanceInMap.

If that sounds like a lot of work, a simpler version might loop overall points, add each one with its distance measurement to the map, sort the map, and then return the first k items. The downside of this implementation is that for a dataset of a million points, you’d need to build a distance map of a million points and then sort that giant list in memory.

In your version, you only ever hold k items as candidates, so you never need to store a separate million-point map. Your version does require a call to Array.sort whenever an item is added to the map. This is inefficient in its own way, as the sort function is called for each addition to the map. Fortunately, the sort operation is only for k items, where k might be something like 3 or 5.

The computational complexity of the sorting algorithm is most likely O(n log n) (for a quicksort or mergesort implementation), so it only takes about 30 data points for the sophisticated version to be more efficient than the simple version when k = 3, and for k = 5, this happens at around 3,000 data points. However, both versions are so fast that for a dataset smaller than 3,000 points, you won’t notice the difference.

  1. Finally, tie the algorithm together with the predict The predictmethod must accept a test point, and at the very least, return the determined label for the point. You can also add some additional output to the method and report the labels of the k nearest neighbors as well as the number of votes each label contributed. Add the following to the body of the KNN class:

This method requires a little bit of datatype juggling in JavaScript but is simple in concept. First, generate your distance map using the method you just implemented. Then, remove all data except for the k nearest points and store that in a votes variable. If you’re using 3 as k, then votes will be an array of length three.

Now that you have your k nearest neighbors, you need to figure out which label represents the majority of the neighbors. You can do this by reducing your votes array into an object called voteCounts. To get a picture of what you want voteCounts to look like, imagine that you’re looking for the three nearest neighbors and the possible categories are Male or Female. The voteCounts variable might look like this: {“Female”: 2, “Male”: 1}.

The job is still not done, however—after reducing your votes into a vote-count object, you still need to sort that and determine the majority label. You can do this by mapping the vote counts object back into an array and then sorting the array based on vote counts.

There are other ways to approach this problem of tallying votes; any method you can think of will work, as long as you can return the majority vote at the end of the day. That’s all you need to do in the knn.js file. The algorithm is complete, requiring fewer than 70 lines of code.

Now set up your index.js file and get ready to run some examples. Remember that you need to download the data.js file first. You can do this by downloading the file from https://github.com/bkanber/MLinJSBook. Now add the following to the top of index.js:

You can now try out the algorithm using a simple example.

Example – Height, weight, and gender

KNN, like k-means, can work on high-dimensional data—but, like k-means, you can only graph example data in a two-dimensional plane, so keep your example simple. The first question you’ll tackle is: can you predict a person’s biological sex given only their height and weight?

The data for this example has been downloaded from a national longitudinal survey on people’s perception of their weight. Included in the data are the respondents’ height, weight, and gender. This is what the data looks like when graphed:

Just by looking at the preceding charted data, you can get a sense as to why KNN is so effective at evaluating clustered data. It’s true that there’s no neat boundary between male and female, but if you were to evaluate a new data point of a 200 pound, 72 inches-tall person, it’s clear that all the training data around that point is male and it’s likely your new point is male, too.

Conversely, a new respondent at 125 pounds and a height of 62 inches is well into the female area of the graph, though there are a couple of males with those characteristics as well. The middle of the graph, around 145 pounds and 65 inches tall, is the most ambiguous, with an even split of male and female training points. Expect the algorithm to be uncertain about the new points in that area. As there is no clear dividing line in this dataset, you would need more features or more dimensions to get a better resolution of the boundaries.

In any case, try out a few examples. Pick five points that you may expect to be definitely male, definitely female, probably male, probably female, and indeterminable. Add the following code to index.js, beneath the two import lines:

Run yarn start from the command line and you should see the following output. Since the KNN is not stochastic that is it does not use any random conditions in its evaluation, you should see exactly the same output with the possible exception of the ordering of votes and their indexes, if two votes have the same distance.

If you get an error when you run yarn start, make sure that your data.js file has been correctly downloaded and installed.

Here’s the output from the preceding code:

The algorithm has determined genders just as you would have done, visually, by looking at the chart. Feel free to play with this example more and experiment with different values of k to see how results might differ for any given test point.

If you found this article interesting, you can explore Burak Kanber’s Hands-on Machine Learning with JavaScript to gain hands-on knowledge on evaluating and implementing the right model, along with choosing from different JS libraries, such as NaturalNode, brain, harthur, and classifier to design smarter applications. This book is a definitive guide to creating an intelligent web application with the best of machine learning and JavaScript.

How to Troubleshoot Common Angular Errors

Learn how to optimize your troubleshooting tools and became aware of the common Angular errors you might encounter while developing applications.

Debugging Tools

In this article, you will intentionally introduce an easy-to-make mistake so that you can become familiar with real-life errors that can happen while developing your applications and gain a solid understanding of the tool that makes make you an effective developer.

Now pretend that you have made an innocent mistake when copying and pasting the URL from the API documentation page on OpenWeatherMap.org and forgot to add http:// in front of it. This is an easy mistake to make:

Your app will compile successfully, but when you inspect the results in the browser, you won’t see any weather data. In fact, it seems like the Current Weather component is not rendering at all, as you can see in the image below:

Current Weather Does Not Render

There are many ways to debug angular errors for application or any JavaScript application here are some of this:

Debugging with Chrome Developer Tools

You can use the Google Chrome browser because of its cross-platform and consistent developer tools with helpful extensions.

Open Chrome Developer Tools (dev tools) on macOS by pressing option + ⌘ + I or on Windows by pressing F12 or CtrlShift + I.

As a best practice, you write code with VS Code and the browser open side by side, while the dev tools are also open in the browser. There are several good reasons for practicing side-by-side development:

  • Fast feedback loops: With live-reloading, you see the end result of your changes very quickly
  • Laptops: A lot of developers do most of their development on a laptop and a second monitor is a luxury
  • Attention to responsive design: As you may have limited space to work with, you can constantly pay attention to mobile-first development, fixing desktop layout issues after the fact
  • Awareness of network activity: To enable you to quickly see any API call errors and also ensure that the amount of data that is being requested remains in line with your expectations
  • Awareness of console errors: To enable you to quickly react and troubleshoot when new errors are introduced

Observe how side-by-side development looks like:

Side-by-side development with live-reloading running

Note that ultimately, you should do what works best for you. With the side-by-side setup, you will frequently find yourself toggling VS Code’s Explorer on and off and resizing the dev tools pane to a larger or smaller size depending on the specific task at hand. To toggle VS Code’s Explorer, click on the Explorer icon circled in the preceding screenshot.

Just as you can do side-by-side development with live-reloading using npm start to solve angular errors. You can get the same kind of fast feedback loops for unit testing using npm test:

Side-by-side development with unit testing

With the side-by-side unit testing setup, you can become very effective in developing unit tests.

Optimizing Chrome Dev Tools

For the side-by-side development with live-reloading to work well, you need to optimize the default dev tools experience:

Optimized Chrome Developer Tools

Looking at the preceding figure, you will note that numerous settings and information radiators are highlighted:

  1. Have the Network tab open by default so that you can see network traffic flowing.
  2. Open the dev tools settings by clicking on the
  3. Click on the right-hand side icon so that dev tools dock on the right-hand side of Chrome. This layout gives more vertical space, so you can see more network traffic and console events at once. As a side benefit, the left-hand side takes the rough size and shape of a mobile device.
  4. Toggle on large request rows and toggle off overview to see more of the URL and parameters for each request and gain more vertical space.
  5. Check the option Disable cache, which will force reload every resource when you refresh a page while the dev tools are open. This prevents bizarre caching errors from ruining your day.
  6. You will mostly be interested in seeing XHR calls to various APIs, so click on XHR to filter results.
  7. Note that you can glance at the number of console errors in the upper-right corner as 12. The ideal number of console errors should be at all times.
  8. Note that the top item in the request row indicates that there’s an error with status code 404 Not Found.
  9. Since you’re debugging an Angular application, the Augury extension has been loaded.

With your optimized dev tools environment, you can now effectively troubleshoot and resolve the application error from earlier.

Troubleshooting network issues

There are three visible issues with the app at this state:

  • The component details aren’t displaying
  • There are numerous console errors
  • The API call is returning a 404 not found error

Begin by inspecting any network errors, since network errors usually cause knock-on effects:

  1. Click on the failing URL in the Network
  2. In the Details pane that opens to the right of the URL, click on the Preview
  3. You should see this:

By just observing this error message, you will likely miss the fact that you forgot to add the http:// prefix to the URL. The bug is subtle and certainly not glaringly obvious.

  1. Hover over the URL and observe the full URL, as shown:

Inspecting Network Errors

As you can see, now the bug is glaringly obvious. In this view, you will get to see the full URL, and it becomes clear that the URL defined in weather.service.ts is not fully qualified, so Angular is attempting to load the resource from its parent server, hosted on localhost:5000, instead of going over the web to the right server.

Investigating console errors

Before you fix this issue, it is worthwhile to understand the knock-on effects of the failing API call:

  1. Observe the console errors:

Dev Tools Console Error Context

The first element of note here is the ERROR CONTEXT object, which has a property named DebugContext_. The DebugContext_ contains a detailed snapshot of the current state of your Angular application when the error happened. The information contained within DebugContext_ is light years ahead of the amount of mostly unhelpful error messages AngularJS generates.

Note that properties that have the value (…) are property getters, and you must click on them to load their details. For example, if you click on the ellipsis for componentRenderElement, it will be populated with the app-current-weather element. You can expand the element to inspect the runtime condition of the component.

  1. Now scroll to the top of the console.
  2. Observe the first error:

You have probably encountered the TypeError before. This error is caused by trying to access the property of an object that is not defined. In this case, CurrentWeatherComponent.current is not assigned to an object, because the http call is failing. Since current is not initialized and the template blindly tries to bind to its properties like {{current.city}}, you will get a message saying property ‘city’ of undefined cannot be read. This is the kind of knock-on effect that can create many unpredictable side-effects in your application. You must proactively code to prevent this condition.

Karma, Jasmine, and Unit Testing errors

When running tests with the ng test command, you will encounter some high-level errors that can mask the root cause of the actual underlying errors.

The general approach to resolving errors should be inside out, resolving child component issues first and leaving parent and root components for last.

Network Error

Network errors can be caused by a multitude of underlying issues:

Working inside out, you should implement test doubles of services and provide the fakes to the appropriate components. However, in parent components, you may still encounter errors even if you correctly provided fakes.

Generic ErrorEvents

Error events are generic errors that hide the underlying cause:

To expose the root cause of a generic error, implement a new test:debug script:

  1. Implement test:debug, as shown, in json:

  1. Execute npm run test:debug.
  2. Now the Karma runner will likely reveal the underlying issue.
  3. If necessary, follow the stack trace to find the child component that may be causing the issue.

Note that if this strategy is not helpful, you may be able to glean more information on what’s going wrong by breakpoint debugging your unit tests.

Debugging with Visual Studio Code

You can also debug your Angular application, Karma, and Protractor tests from directly within Visual Studio Code. First, you need to configure the debugger to work with a Chrome debugging environment, as illustrated:

VS Code Debugging Setup

  1. Click on the Debug
  2. Expand the No Configurations drop-down and click on Add Configuration….
  3. In the Select Environment select box, select Chrome.

This will create a default configuration in the .vscode/launch.json file. You can modify this file to add three separate configurations.

  1. Replace the contents of jsonwith the following configuration:

  1. Execute the relevant CLI command like npm start, npm test, or npm run e2ebefore you start the debugger.
  2. On the Debugpage, in the Debug drop-down, select npm start and click on the green play icon.
  3. Observe that a Chrome instance has launched.
  4. Set a breakpoint on a .ts
  5. Perform the action in the app to trigger the
  6. If all goes well, Chrome will report that the code has been Paused in Visual Studio Code.

Note that this method of debugging doesn’t reliably work. You may have to manually set a breakpoint in Chrome Dev Tools | Sources tab, finding the same .ts file under the webpack://. folder, which will then correctly trigger the breakpoint in VS Code. However, this renders the entire benefit of using VS Code to debug code useless. For more information, follow the Angular CLI section on VS Code Recipes on GitHub at https://github.com/Microsoft/vscode-recipes.

If you liked this article, you can learn more about Angular 6 in Doguhan Uluca’s Angular 6 for Enterprise-Ready Web Applications to follow a hands-on and minimalist approach demonstrating how to design and architect high-quality apps.

Customizing a Simple Social Media Application Using MERN

Learn how to use the MERN stack to build simple social media application features in this tutorial by Shama Hoque.

MERN Social

MERN Social is a sample social media application, used for the purpose of this article, with rudimentary features inspired by existing social media platforms such as Facebook and Twitter. In this article, you’ll learn how to update a user profile in MERN Social that can display a user uploaded profile photo and an about description.

The main purpose of this application is to demonstrate how to use the MERN stack technologies to implement features that allow users to connect and interact over content. You can extend these implementations further, as desired, for more complex features.

The code for the complete MERN Social application is available on GitHub in the repository at github.com/shamahoque/mern-social. You can clone this code and run the application as you go through the code explanations. Note that you will need to create a MERN skeleton application by adding a working React frontend, including frontend routing and basic server-side rendering of the React views for following these steps.

The views needed for the MERN Social application can be developed by extending and modifying the existing React components in the MERN skeleton application. The following component tree shows all the custom React components that make up the MERN Social frontend and also exposes the composition structure that you can use to build out extended views:

Updating the user profile

The skeleton application only has support for a user’s name, email, and password. However, in MERN Social, you can allow users to add their description and also upload a profile photo while editing the profile after signing up:

Adding an about description

In order to store the description entered in the about field by a user, you need to add an about field to the user model in server/models/user.model.js:

Then, to get the description as input from the user, you can add a multiline TextField to the EditProfile form in mern-social/client/user/EditProfile.js:

Finally, to show the description text added to the about field on the user profile page, you can add it to the existing profile view in mern-social/client/user/Profile.js:

With this modification to the user feature in the MERN skeleton code, users can now add and update a description about them to be displayed on their profiles.

Uploading a profile photo

Allowing a user to upload a profile photo will require that you store the uploaded image file and retrieve it on request to load in the view. For MERN Social, you need to assume that the photo files uploaded by the user will be of small sizes and demonstrate how to store these files in MongoDB for the profile photo upload feature.

There are multiple ways of implementing this upload feature considering the different file storage options:

  • Server filesystem: Upload and save files to a server filesystem and store the URL to MongoDB
  • External file storage: Save files to an external storage such as Amazon S3 and store the URL in MongoDB
  • Store as data in MongoDB: Save files of a small size (less than 16 MB) to MongoDB as data of type Buffer

Updating the user model to store a photo in MongoDB

In order to store the uploaded profile photo directly in the database, you can update the user model to add a photo field that stores the file as data of type Buffer, along with its contentType in mern-social/server/models/user.model.js:

Uploading a photo from the edit form

Users should be able to upload an image file from their local files when editing the profile. You can update the EditProfile component in client/user/EditProfile.js with an upload photo option and then attach the user selected file in the form data submitted to the server.

File input with Material-UI

You can use the HTML5 file input type to let the user select an image from their local files. The file input will return the filename in the change event when the user selects a file in mern-social/client/user/EditProfile.js:

To integrate this file input with Material-UI components, you can apply display:none to hide the input element from view, then add a Material-UI button inside the label for this file input. This way, the view displays the Material-UI button instead of the HTML5 file input element in mern-social/client/user/EditProfile.js:

With the Button‘s component prop set to span, the Button component renders as a span element inside the label element. A click on the Upload span or label is registered by the file input with the same ID as the label, and as a result, the file select dialog is opened. Once the user selects a file, you can set it to state in the call to handleChange(…) and display the name in the view in mern-social/client/user/EditProfile.js:

Form submission with the file attached

Uploading files to the server with a form requires a multipart form submission. You can modify the EditProfile component to use the FormData API to store the form data in the format needed for encoding type multipart/form-data.

First, you need to initialize FormData in componentDidMount() in mern-social/client/user/EditProfile.js:

Next, you need to update the input handleChange function to store input values for both the text fields and the file input in FormData in mern-social/client/user/EditProfile.js:

Then, on clicking submit, this.userData is sent with the fetch API call to update the user. As the content type of the data sent to the server is no longer ‘application/json’, you’ll also need to modify the update fetch method in api-user.js to remove Content-Type from the headers in the fetch call in mern-social/client/user/api-user.js:

Now if the user chooses to upload a profile photo when editing profile, the server will receive a request with the file attached along with the other field values.

Processing a request containing a file upload

On the server, to process the request to the update API that may now contain a file, you need to use the formidable npm module:

Formidable will allow you to read the multipart form data, giving access to the fields and the file, if any. If there is a file, formidable will store it temporarily in the filesystem. You need to read it from the filesystem, using the fs module to retrieve the file type and data and store it in the photo field in the user model. The formidable code will go in the update controller in mern-social/server/controllers/user.controller.js as follows:

This will store the uploaded file as data in the database. Next, you’ll need to set up file retrieval to be able to access and display the photo uploaded by the user in the frontend views.

Retrieving a profile photo

The simplest option to retrieve the file stored in the database and show it in a view is to set up a route that will fetch the data and return it as an image file to the requesting client.

Profile photo URL

You need to set up a route to the photo stored in the database for each user and also add another route that will fetch a default photo if the given user has not uploaded a profile photo in mern-social/server/routes/user.routes.js:

You need to look for the photo in the photo controller method and if found, send it in the response to the request at the photo route; otherwise, you’ll need to call next() to return the default photo in mern-social/server/controllers/user.controller.js:

The default photo is retrieved and sent from the server’s file system in mern-social/server/controllers/user.controller.js:

Showing a photo in a view

With the photo URL routes set up to retrieve the photo, you can simply use these in the img element’s src attribute to load the photo in the view in mern-social/client/user/Profile.js. For example, in the Profile component, you’ll get the user ID from state and use it to construct the photo URL.

To ensure that the img element reloads in the Profile view after the photo is updated in the edit, you need to also add a time value to the photo URL to bypass the browser’s default image caching behavior.

Then, you can set the photoUrl to the Material-UI Avatar component, which renders the linked image in the view:

The updated user profile in MERN Social can now display a user uploaded profile photo and an about description:

If you found this article helpful, you can explore Shama Hoque’s Full-Stack React Projects to unleash the power of MERN stack. This book guides you through MERN stack-based web development, for creating a basic skeleton application and extending it to build four different web applications.