Making Conditional HTTP Requests

 · 7 min read
 · Aaron Kyle
Last updated: August 28, 2022
Table of Contents

Get My Content Delivered To Your Inbox

    No Spam, Pinky Promise.

    What Is Real-World Problem Solving

    The goal of the real-world problem solving series is not to solve the hardest or easiest problems. I'll leave that to the competitive programmers. It's meant to discuss problems actually experienced. It's meant to discuss problems you actually see. I solve a ton of coding challenges, see here, and honestly, it's great practice and a way to strengthen your logic skills, but 9 times out of 10 I don't see it on a daily basis in my own personal work.

    I really had no idea what type of problems/solutions I would come across when I entered the industry. 2 Years later, I feel much more comfortable in terms of setting personal expectations for problems I'll come across.

    If you can loop a deeply nested array, access data in bad JSON objects, know all about conditionals, can read documentation, watch a few tutorials, and use your debugging tools well, there's a good chance you'll be alright. Of course it's not "that simple" as nothing is, but everything isn't a LeetCode Medium or Hard either.

    Okay, let's discuss this week's problem...

    What Are We Solving


    We're crafting a solution for making POST requests that won't always have the same key/values entered. If the data has been entered, we want it sent. It it wasn't, we want to leave the keys associated with that bit of data out of the request.

    • Problem Part of The Stack: Front-End
    • Language: JavaScript
    • Framework: React

    Problem Explained


    You're building an inventory manager and currently working on the ability to Create/Add a New Product. This new product is added through form submission by making a HTTP(client) request to the database(server) via a POST method.

    The inventory system can take 3 different physical measurements for each added item: - Tube - Box - Container

    The only REQUIRED physical measurement is a Tube, the smallest unit. Box and Container measurements are optional.

    If Box and Container measurements aren't entered at time of product creation, when the POST request is made, there will be empty stored key/values sent to the database. The team has made a request:

    • Instead of passing empty values in the request, implement functionality to create a resizable/dynamic object. This functionality will be dynamic in the sense that it can conditionally:

    • Add A Box and/or Container data if the physical measurements for each were added by the user and

    • Send the object with only the Each physical measurements.
    • Verify what was/wasn't entered and Send The Correct JSON Data

    How would you solve this?

    This is programming, so I would imagine that there are many ways, better and worse, to handle this.

    Solution


    In 5 Steps, What I chose to do was:

    1. Remove the keys from the object that are tied to box physical measurements
    2. Remove the keys from the object that are tied to container physical measurements
    3. Create an additional 2 objects that will store the box and container data separately. In our case, let's just call them the boxObject and the containerObject since they will essentially have the key/values that are associated with their unit of measurement.
    4. Create a function that will serve as the trigger to add necessary data that will be passed in the POST request. We'll simply call it addDataToObj .
      • You will need to check if a specific value in the case/pallet object is undefined.
      • If so, that means that the required data wasn't entered during form submission.
        • NOTE: Of course, from a front-end perspective you could easily set up form validation for specific fields, but in our case, it's purposely left optional/open-ended. Not every item will always come in multiple units of measurement, and there is no way to know what will or won't be entered.
      • Ultimately, the Unit(s) of Measurement(boxObj or containerObj) with missing data will not be going as a part of the JSON sent to the database.
      • If it ISN'T undefined, that means data was entered for that UOM at time of entry. It will need to be a part of the request.
    5. Find a suitable place to trigger this addDataToObj function to run. In my case, I called it in the function that makes the request, makePostRequest. This is completely up to you and how the application is designed.

    Code Sample


        ...
        # Storage of Values Entered Into Form
        const [tubeWeight, setTubeWeight] = useState('')
        const [tubeLength, setTubeLength] = useState('')
        const [tubeHeight, setTubeHeight] = useState('')
        const [tubeWeight, setTubeWeight] = useState('')
        const [boxWeight, setBoxWeight] = useState('')
        const [boxLength, setBoxLength] = useState('')
        const [boxHeight, setBoxHeight] = useState('')
        const [containerWeight, setContainerWeight] = useState('')
        const [containerLength, setContainerLength] = useState('')
        const [containerLength, setContainerLength] = useState('')
    
        # Required Object for POST HTTP Request
        const newItemDataToSend = [{
            product-type: productType
            weight: tubeWeight,
            length: tubeLength,
            height: tubeHeight,
            itemCreationDetails: {
                creationDate&Time: currentTime,
                createdBy: currentUser,
            }
        }]
    
        # Objects for Optional Units of Measurement
        const boxObj = {
            weight: boxWeight,
            length: boxLength,
            height: boxHeight
        }
        const containerObj = {
            weight: containerWeight,
            length: containerLength,
            height: containerHeight
        }
    
        # Function Checks If Additional UOM Data Was Entered
        def addDataToObj = () => {
            if(boxWeight !== '') newItemDataToSend.push(boxObj)
            if(containerObj !== '')newItemDataToSend.push(containerObj)
        }
    
        # Function Makes The POST Request
        def makePostRequest = () => {
            addDataToObj()
            fetch(`${api}`, {
                method: 'POST',
                headers: {
                    'Authorization': `${authorizationKey}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(newItemDataToSend)
            })
        }
    
        return(
        <div>
            <Button onClick={makePostRequest}>
                <Text>
                    Add New Product
                <Text>
            </Button>
        <div/>
        )
        ...
    

    Get My Content Delivered To Your Inbox

      No Spam, Pinky Promise.