Photo by Sebastián León Prado on Unsplash

A Simple Way to Send a Patch Request In Redux

Sitting back after a long day and watching my favorite actors is one of my favorite hobbies. As a child, my father and I used to spend time together in comfortable silence as we watched endless hours of Star Trek: The Next Generation, Little House on the Prairie, and various movies that were edited for television.

A while back I wrote about an application I was putting together to track the television programs I like to watch. I wanted to be able to make notes about my favorite episodes, actors, and guest stars, as well as add shows to a Watchlist.

That's my face judging how behind I am on my shows.

One of the larger hurdles was adding and removing my show from that Watchlist. I was working on doing full CRUD for my programs and the Update function was particularly vexing.

Initially, I was decided to manipulate my array by using JSON.stringify and JSON.parse to make a hard copy. I turned the array of programs into string, then back to an object, which then allowed me to update the property that toggled my heart button.

case ‘TOGGLE_WATCHLIST’:
    let stringifiedPrograms = JSON.stringify(state.programs)
    let copyOfPrograms = JSON.parse(stringifiedPrograms)
    let programToBeToggled = copyOfPrograms.find(program =>      program.id === action.id)
    programToBeToggled.watchlist = !action.watchlist
return {}

While it worked for my purposes, you can see that it’s kind of complicated and hard to follow.

After I completed the project, I decided to go back and refactor the section. Turns out, it’s easier to make a copy and pass it into case statement code I already had.

    case 'TOGGLE_WATCHLIST':    
      let programsWithNewToggle = state.programs.map(program => {
        if (program.id === action.payload.id) {
          return action.payload
          }
          else {
            return program
          }
        })

      return {...state, programs: programsWithNewToggle }

Above, you can see some my reducer which contains a case called ‘TOGGLE_WATCHLIST’. Coincidentally, my cases to remove and add a comment also include the same solution, so they are stacked above this one.

Anyway, I elected to return the entire program object from my fetch request. As a result, I chose to iterate through my state to find the action id that matches my updated program id. When found, I return that updated program. If I never find an id to match, my function will do nothing but display non-matching programs.

The case returns an object comprised of a copy of my state, but updates the value of my original array with the new array called programsWithNewToggle.

Hopefully, you enjoyed this explanation and found something that you can apply to your next Redux project. If you want to delve deeper, here are some great resources to get you started: