Like/dislike content or remove vote

Web development

I’m building an app around YouTube iframe api (which I wrote about already), where user can like/dislike content (a type of video which is a compilation of songs that can be targeted by time) or removing vote if clicking on the same vote type again. For example if user clicks on like button for the second time in a row, vote gets removed and page appears as user haven’t voted yet.

To do that I’m first deleting a record if exactly the same vote type is already associated with a user and a compilation. The result returned contains the number of how many rows were actually affected (deleted) in the process.

  • If there were rows deleted, this means user clicked same vote type again and we finish with request processing.
  • If not, we perform insert into ... on duplicate key update ... operation, because we need to record a vote if user decided to like/dislike content. Or change it if user changed his mind and instead i.e. to like the content he wants to dislike it.

In Laravel, this can be done in something like that (in controller):

public function storeVote(int $compilationId, Request $request)
{
    $vote   = $request->post('vote');
    $userId = $request->user()->id;

    $data = [
        'compilation_id' => $compilationId,
        'user_id'        => $userId,
        'vote'           => $vote
    ];

    $deletedRows = $this->compilationLike->where($data)->delete();
    
    if ($deletedRows != 0) {
        return back()->with('status', 'Vote removed');
    }

    $compilationLike = $this->compilationLike->updateOrCreate([
        'compilation_id' => $compilationId,
        'user_id'        => $request->user()->id
    ], [
        'vote'           => $vote
    ]);

    $status = $compilationLike->wasRecentlyCreated ? 'Vote saved' : 'Vote changed';

    return back()->with('status', $status);
}

Off-topic: Notice the use of wasRecentlyCreated for displaying appropriate status message. With it we can find out if record was inserted or updated.

YouTube iframe API example

YouTube iframe API

Web development

YouTube iframe API lets developers control embedded YouTube video on a website. They can for example stop or pause the player, react on player state changes or add their own event listener. I familiarise with it with a YouTube video that’s in fact compilation of couple of songs and I beside it was an ordered list of those songs and I wanted the currently played song to be styled differently.

The idea came to mind when I saw YouTube videos that have in descriptions time markers for each song indicating it start and when you click it it rewinds player to that time.

Here is this example.

User clicks on a song from this list and player moves to the position of this song and starts to play. And song currently being played is styled with bigger font so the user can spot it easily. User can also click on player timeline and song played will be highlighted. I also didn’t forget the scenario when one song ends and another begins so the appropriate song is marked as currently played.

Things to note:

  • Examples from official docs aren’t working because iframe API has changed the way how code runs when iframe API is ready. You need to pass a player initialisation code to YT.ready function, not define onYouTubeIframeAPIReady (I only figured this out by inspecting https://www.youtube.com/iframe_api, which fortunately doesn’t have many lines).
  • YouTube video ID is e.g. bHQqvYy5KYo and not v=bHQqvYy5KYom which is what follows after question mark in URL address.
  • You can create YouTube video player from scratch from JavaScript or use existing iframe as I did. Consult docs and see the 1st example on how to do it.
  • You can get a thumbnail for a YouTube video just by grabbing its ID and depending on desired quality insert it in a URL pattern. All URL patterns are listed in the linked stackoverflow answer (i didn’t use this feature in the demo, but in an app I decided to built later around this iframe api).

All-girl Lord of the Flies remake

News

An all-girl cast for Lord of the Flies remake is in the making. I found this while looking at Twitter’s trending hashtags this morning. Having read this classic few month ago on my Kindle, I wondered though how this could possibly work. William Goldberg who wrote it 50 years ago, come up with a brief idea, quoting “Wouldn’t it be a good idea to write a story about some boys on and island, showing how they would really behave, being boys and not saints as they usually are in children’s books”. He’s also well known for a following quote which he stated in an answer why his novel features boys and not girls: “I think women are foolish to pretend they are equal to men, they are far superior and always have been.”

In a novel, boys without any adult get stranded on a isolated island and shortly after they form two groups, one trying to maintain order, building shelters and signal fire while waiting to be rescued by adults, other turning to hunting and only hunting animals. It’s about civilization vs. savagery and men’s nature.

I just don’t believe girls aged 8-12 would react in the same manner. I’m not saying they will probably try to find shelter, build a fire and go picking fruits from trees and the grounds but that’s what they did in stone age when roles of men and women were well defined (men hunted, women stayed at home and tend to children). Just as boys turned to instincts so will girls.

Given all said I think the latest “equality” attempt from Hollywood is a disrespect to this classic read and to women. The two writers, ironically both male, basically want to degrade women. And it misses the point of the book. I’d much likely view realistic portrayal of how would girls survive in the Lord of the Flies’s settings (not just showing them behaving like boys or that girls can be just as savage as boys).

How to reduce amount of dispatched actions in Redux

Web development

When I was beginner in using Redux to manage state in JavaScript while using React, I often dispatched unnecessary amount of actions when I could be done with just one or two. Or when I was loading initial data when user visits website, I often dispatched an action that set only specific resource. Something like this:

const fetchAppData = () => dispatch => apiClient.fetchAppData()
    .then(res => res.json())
    .then(res => {
        if (res.error) {
            dispatch(actions.showNotification(res, false))
            return
        }
        dispatch(actions.setUser(res.users)) // action type is SET_USER
        dispatch(actions.setPosts(res.posts)) // action type is SET_POSTS
    })

I eventually figured it out Redux store can handle one action in multiple reducers at the same time so the two dispatch lines became one dispatch(actions.setAppData(res)). Action type is SET_APP_DATA and is defined as case in both reducers as opposed to SET_USER which is defined only in users reducer and SET_POSTS only in posts reducer.

Another use case when you can reduce amount of dispatched actions is when you set a data and at the same time you want to display a notification. Following the previous example we could have another reducer for notifications that sets state of notification to {type:'SUCCESS', message: 'Data loaded'} when SET_APP_DATA is dispatched.

Billy Lynn's Long Halftime Walk

Billy Lynn’s Long Halftime Walk

TV/Movies

“Billy Lynn’s Long Halftime Walk” is a movie with a boring title, but it turned out to be quite good and make you think! On one side you have soldier’s sister who doesn’t want her brother to go back to Iraq, on other an American show-business which glorify American soldiers (making them parading in halftimes shows of a American football matches) but when it comes to show actual value for them, it feels they don’t respect them. There also comes a cheerleader in a mix but she’s only interested in soldier as long as he is Billy Lynn, the hero soldier. It is implied that if he’d decide to leave army for her, she’d dump him the first moment she sees him. Soldier struggles all the time with his feeling during the movie and has flashbacks to the event that earned him and his squad a recognition.

I really like emotional side of the story and felt bad for Billy Lynn. Perhaps the most touching are scenes with his sister, played by Kristen Stewart, who really cares for him. At the end when she’s defeated in persuading him to stay, she remains on his side.