Back to Top

What 9 social media leaders are taking with them into 2021

What a year it’s been.

Over the last nine months, social media leaders have dealt with a global pandemic, natural disasters, social uprisings and a contentious general election. With people spending more time on social media because they’re stuck at home, social teams are also under pressure to be always on. Many social media marketing leaders also had to scrap their original strategies because they were no longer relevant or appeared inconsiderate. In short, 2020 was a year most of us would like to forget.

But for all the ups and downs it brought, 2020 was also a (albeit, at times, stressful) growth opportunity for social media leaders. And the social media lessons learned can be applied toward future strategies in a post-pandemic, post-election year. Read on to discover what lessons nine leaders in social media are taking with them into the new year.

1. Listen, listen, listen

Working in social media means working in a fast-paced environment. But for as quickly as social teams move, there’s value in knowing when to slow down and really look at what’s happening around you. Lindsay Bruce, the marketing manager of SMB at Twitter, shares her thoughts on why listening is going to be an important tool in 2021.

“It’s always a good idea to read the room before posting on social, but this year it became especially critical. Before every Tweet, I looked at the day’s headlines, trending conversations and looked to see if/how other brands were engaging.

I plan to continue taking those few extra minutes to get a feel for the day’s (or week’s or minute’s) climate. Not only can it save you from posting insensitive content, but it can help you identify meaningful ways to connect that day.”

2. Lean into uncertainty—but proceed with caution

When plans start to go awry, it’s our instinct to want to pump the brakes and fix the situation. But as we saw with 2020, sometimes it’s better to just go with the flow. That’s one lesson Austin Braun, social media manager at the University of Colorado College of Engineering and Applied Science, is taking with him into 2021.

“Embrace the unexpected—but more importantly, learn to love it. 2020 proved that a great social media manager is one that can think quickly and execute on a whim. Whether [that’s] halting content in times of crisis or jumping onto an ad-hoc trend, trusting your gut instinct to protect (or enhance) your brand is invaluable.

Likewise, thinking critically about the way your brand’s tone, persona and message will be perceived is [something] all social media managers should consider before publication. Think through each pitfall and always think of the end at the beginning.”

3. Take care of your people

One of the best things about social media is its ability to bring brands and people together to form a community. And this year highlighted just how powerful communities can be when we take the time to listen to and take care of each other. Brianna Foster, the social media manager at Pinterest, has this to share with her fellow social media leaders.

“2020 was the year that really emphasized community management. Listening to what your audience is saying, monitoring social trends and keeping a pulse on social movements proved to be more valuable than any other strategy. This year we really had to throw away any initial ideas of the work we had planned to do and really sit down with our audiences and see how we could better serve them in this state of the world.”

4. Lead with your brand’s values

In 2020, more brands than ever before took a stand on a variety of social issues. If speaking up is part of your strategy, you need to be ready to back it up. Jayde Powell, head of social and community at Sunwink, elaborates on what marketers need to consider before taking a stand.

“Values-led marketing matters. If there’s anything that 2020 taught us, it’s that consumers want to purchase from brands that are on the right side of history. This year, we saw several brands use their platforms to speak on social injustice; however, social injustice wasn’t just a 2020 issue. Social injustices happen every single day and have been happening for centuries.

Using social to speak out on issues facing marginalized communities, amplifying the voices of marginalized individuals and shedding a light on issues impacting our earth is the future of social media marketing. I believe that if a brand’s social media marketing strategy isn’t rooted in its values, then their community will navigate elsewhere.”

5. It’s not all about you

While consumers expect brands to promote their products and services on their social profiles, there are times when consumers get tired of seeing a brand talk only about themselves. Pushing a promotion when people are struggling to find employment, for example, comes off as insensitive. Pat Timmons, the social media associate at Drift, expands upon this observation:

“Your audience doesn’t want to hear about brand non-stop. They want you to provide them value that is relevant to how they feel in that moment. Meet your audience where they are and put them at the center of everything you do.”

6. Don’t be afraid to break the fourth wall

Despite being best practice to follow brand and style guidelines for social, there are times when it’s okay to break character and speak directly to your audience. Brands like Wendy’s and Steak-umm have distinct personalities on Twitter and Tweet like a human being would. Alexa Heinrich, the social media manager at St. Petersburg College, shares her learnings from 2020:

“Sometimes it’s okay to break the fourth wall with your social media. Your audience is actually very okay in most instances with you humanizing a brand. Personally, I’m also planning to be better about setting boundaries for myself to maintain my mental wellness in a very fast job setting.”

7. Speak from your (brand’s) heart

This year was an emotional roller coaster for many, further emphasizing the importance of being kind to one another. For brands, this can be as simple as checking in with consumers and acknowledging that times are tough. Brianne Fleming, a marketing instructor at the University of Florida, doubles down on this important reminder everyone should keep in mind as they plan for 2021.

“Marketers know empathy is important, but it was the true essence of 2020. As I head into 2021, I’ll remind myself that no matter what social media innovations are introduced, people will always respond to compassion and powerful stories that speak to the heart.”

8. Perfection is overrated

A polished social presence may be nice to look at, but how effective is it in helping your brand achieve its goals? Curating a perfect social account takes time and resources that could be spent on more impactful content that feels less sophisticated but resonates strongly with your audience. Christina Garnett, senior insights strategist at VIZIT, shares advice for brands on how to improve their social content.

“Social connection isn’t built through perfection. It’s built through relatability. Brands and personal accounts are creating the most buzz when they are starting conversations, showing what’s behind the curtain and sharing their human (flawed) side. Consumers want to connect with brands that understand them. McDonald’s has done an incredible job in harnessing the voice and emotion of their consumers.”

9. Make time for yourself

Few teams were put through the wringer like the social team was in 2020. Some feel like they haven’t been able to catch a break since March, while others are on the verge of burning out. Working in social media demands a lot out of marketers—which is why it’s important to prioritize self-care and take breaks as needed. Jenn Crim, the acquisition marketing manager for social media at Opry Entertainment Group, offers this reminder for social media leaders as they look ahead to the new year.

“Know when to unplug and turn off the computer and phone. Social media demands a lot out of social media managers, and when you’re on 24/7 (as we often are) it’s easy to get burnt out. Communicate with your leadership when you need a break, a day or some time to unplug. You can’t do your best work when you’re not at your best—and 2020 has definitely reinforced that to me.”

What lessons are you taking into 2021?

2020 is (finally) coming to an end, but there are plenty of social media lessons learned that we can take from this unpredictable and challenging year. Leading with empathy and learning to love the unexpected are just a couple of learnings social marketers can use to elevate their 2021 strategies.

So as you look forward to the new year, don’t forget to take a moment and look back on all that’s happened in 2020. There’s a lot we can learn from our wins and failures in a year that has tested many of us beyond our own limits.

If you’re searching for more inspiration to take your social strategy from good to great, check out our free toolkit for leveling up your 2021 social marketing today.

This post What 9 social media leaders are taking with them into 2021 originally appeared on Sprout Social.

Reblogged 1 year ago from feedproxy.google.com

Haven’t made your New Year’s Resolutions? No worries—you’re not alone

If you’re thinking about giving New Year’s resolutions a hard pass, you’re not the only one.

Social chatter around New Year’s resolutions has been, to be honest, slow to get off the ground in 2020. We used Sprout Social Advanced Listening to learn what was causing this muted response and found only 27,208 messages across Twitter, Instagram, YouTube and Reddit from November 14-December 14. For comparison, one month’s worth of data on Halloween generated 13 million messages across Twitter alone.

There are a couple of factors likely contributing to the dip in conversations surrounding 2021 goal setting. For starters, people are tired. The allostatic load caused by the pandemic, a contentious presidential election and the ongoing fight for social justice has many people feeling stressed and exhausted.

People also have to contend with the unpredictability of 2021. With the future increasingly in flux, there’s a good chance people aren’t making resolutions because they might not be able to keep them.

Brands are always looking for timely trends to jump on, but because of the lingering effects of 2020, marketers will need to adjust their approach to those trends in 2021. Instead of asking what peoples’ goals are, acknowledge the weirdness of this year and let people know it’s okay to skip resolutions this time around. Or offer a distraction by injecting humor into the bleak situation. To learn more about what people have to say (or, in this case, aren’t saying) about New Year’s resolutions, we dug into listening insights. Here’s what we found.

Keep it light on social

A closer look at the New Year’s resolution conversation on Twitter reveals people are finding ways to joke about the upcoming year. Of the 14,664 Tweets we analyzed, 48% of the Tweets had positive sentiment while 37% were neutral and 15% were negative.

Some people pointed out that not having a New Year’s goal for 2020 was the right move…

…while others shared they unexpectedly fulfilled their resolution after all.

One thing we can all agree on is we’ve had plenty of time on our hands this year to crush (or totally ignore) our goals. The word “time” showed up in 1,073 Tweets with varying use cases, with some using the word to indicate too much time spent at home and with family—jokingly, of course.

For brands thinking about jumping on the resolutions bandwagon, don’t be afraid to embrace the absurdity of 2020 and acknowledge now might not be the appropriate time for goal setting. A post about motivation and “new year, new me” could appear insensitive as people deal with disruptions to their holiday plans and stress from the pandemic. It never hurts to check what people are saying online before crafting your post, and consider leaning into humor if your brand feels compelled to say something.

#Goals and #fitness are still in play

That said, some people are still optimistic about 2021, with one YouGov survey revealing 44% of American adults believe 2021 will be a better year for them compared to 2020. And even after a chaotic year, 58% of consumers plan to carry on with making their New Year’s resolutions.

On Twitter, one person shared they are getting a head’s start on their resolutions before the new year.

This optimism is especially prevalent on Instagram, where 5,737 posts contained hashtags like #Goals and #Motivation. Another popular theme on Instagram revolves around working out, with 4,356 Instagram posts containing #Fitness, #Health and #Goals. Given that many fitness trainers and influencers use Instagram for their business, it’s not too surprising to see posts about New Year’s resolution tips dominating the Instagram conversation.

Ready or not, 2021 is almost here

It’s fitting that, after a turbulent year, people are apprehensive about welcoming in a new year. Although chatter around goal-setting is muted, brands can still find a way to acknowledge the transition to 2021. If this past year has taught us anything, it’s that a little humor goes a long way and jokes about resolutions can inject some levity into a person’s timeline.

Of course, resolutions are just one of many traditions that accompany the new year—and it’s unlikely to be the last custom that’s impacted by global events. As you think about the rest of 2021, social listening can help you uncover how people are responding or adjusting certain traditions. If you’re interested in learning what other insights can come from social listening, check out our article on listening for consumer brands or contact us for a free Sprout listening demo today.

This post Haven’t made your New Year’s Resolutions? No worries—you’re not alone originally appeared on Sprout Social.

Reblogged 1 year ago from feedproxy.google.com

What would it take for new search engines to succeed?

Neeva and You.com seek to pick up segments of users overlooked by Google, and with shifting user preferences and increased governmental scrutiny, there might be an opportunity.

Please visit Search Engine Land for the full article.

Reblogged 1 year ago from feeds.searchengineland.com

Google Ads moves campaign goal metric

Google moved around some fun metrics in Google Ads but don’t let these metrics distract you from the metrics that really matter.

Please visit Search Engine Land for the full article.

Reblogged 1 year ago from feeds.searchengineland.com

Crowd marketing: A link building method that only 2% use to rank higher on Google

30-second summary:

  • Link building still plays a prominent role in SERP ranking, even in 2020.
  • Crowd marketing is a technique that is based on building backlinks on forums and communities.
  • Most people don’t use it, and you can take advantage of that.

Crowd marketing: What’s that?

Crowd marketing is one of those often neglected link building methods, that can give you a competitive edge in Google ranking. It is often called forum or community marketing because that’s where those backlinks come from.

In this article, we’re going to discover why this link building strategy is still useful in 2020, the best practices to apply, and things to be aware of. Stay tuned!

Content created in partnership with Crowdo.

Why would crowd marketing benefit your SEO strategy?

There are tens of thousands of niche-relevant forums with a large number of visitors and great metrics. Crowd marketing does not only provide pure SEO gains, but also indirect benefits. Some of the advantages are as follows:

  • A stronger and diversified backlink profile: Links from niche-specific forums can strengthen and diversify your backlink profile. As an outcome, you’ll rank higher on Google Search.
  • More views and more brand awareness: You will get a lot of eyes on your website which is great for brand awareness.
  • Increase in website traffic and prospective customers: Since we’re interested in targeting very specific online communities, you can expect an inflow of traffic to your website, and possibly more leads and customers.

As mentioned above, this technique has been largely underestimated, and that’s actually great! That means you can take full advantage of it and possibly outrank your competitors.

Digital community marketing and its types

There are a dozen sources that could be relevant to perform crowd marketing campaigns. Those include but are not limited to:

  • Blog (comments section): Heavily overused and no longer effective way of building backlinks. Why? Because blog comments aren’t usually moderated well, meaning that it’s an open book for spammers, and that’s not what we are after.
  • Social media and Q&A Websites: Once again, probably effective for brand awareness, not so much for a boost in SEO. Why? Again, low moderation and the fact that all the links from those platforms don’t build up any authority of a backlink profile.
  • Forums/communities: Bingo, we’ve just reached our sweet spot! There is a multitude of forums for every niche, with real human visitors and a high emphasis on moderation and helpful content. That’s what we’re after, as links from those sources can give you a solid boost in SERP.

Forum link building: A checklist and best practices

1. Search for niche-relevant forums

Context is king, and this rule holds for link building as well. Make sure to do a thorough search and handpick only those communities that discuss subjects relevant to your niche.

Here are some tips that can help you along the way:

  • Avoid the so-called “hello threads” where people greet each other and discuss literally everything. Those are useless for SEO purposes.
  • Search for niche-relevant forums. Let’s say you have a car shipping business – you should only search for resources that discuss vehicles.
  • Keep in mind, that there is a limited number of websites relevant to your business. No need to be upset though, because you can also find relevant threads on common forums. For example, if you trade cryptocurrency – you can search for specific threads about crypto on IT forums.
  • If you find any local websites, that’s even better. If you offer a local service and you happen to find a digital community right in your area – that’s an additional bonus point for backlink building purposes.

2. Look at the amount of traffic

You should target popular websites with real human audiences. Websites that receive a high volume of traffic and user engagement look trustworthy in the eyes of Google, and can also put your business right in front of your target audience.

You can use tools like SimilarWeb to estimate the amount of traffic a website receives. There is no right and wrong here, but at Crowdo we would advise you to aim for forums with at least 30,000 visitors per month. Usually, it’s not a good sign if a forum does not receive a lot of traffic, this may indicate that it’s no longer active or it became a hub for spammers with no human audience whatsoever.

Traffic overview chart

3. Look at the metrics (here we go, SEO nerds)

When you decide whether a certain forum will be useful for your backlink campaign, make sure to take a good look at its website metrics. Let’s have a short overview of the important metrics to keep in mind:

  1. DA/DR: This figure indicates the overall strength of the domain. The higher, the better, try to look at websites with 50+ DA.
  2. TF: This metric is based on the trustworthiness of a website, based on the quality of its referring domains. For example, links from educational websites or Wikipedia would have a much higher ranking weight, than links from social profiles.
  3. CF: This figure is based on the number of referring domains. It is useful to see how trendy or viral the webpage is, but it does not say much about the quality of information.
  4. PA/UR: This metric is calculated the same way as DA, but limited to a specific webpage. It comes in handy when you’re looking at a particular forum thread, as it’s a separate page (hence a separate URL).

4. Check whether a forum is properly moderated

In our case moderation refers to the extent to which forum content is being reviewed/removed by admins, as well as their tolerance towards self-promotion or even spam.

Whilst you can use tools that assess the “spam score” of a certain website, it’s better to stick to your judgment. Just spend some time and skim around the forum, look at what people post and what they talk about.

If you see tons of lookalike comments that include the exact same promotion, poor wording, and links, this is a warning sign, that the forum is not being moderated, and thus probably contains a lot of spam – this clearly is a “no go”, because backlinks from those websites are toxic and will do more harm than good for your SEO in the long-run.

On the other hand, forums with aggressive moderation will never let you place any link, even if it fits the context and the discussion. To conclude, medium moderation is usually preferable, because it means that a link can be included ONLY if it’s relevant.

Action time: Writing solid forum replies

Now you know everything you need to pick decent websites for link building. Yet, you’re not a guru of crowd marketing if you don’t know how to use them properly.

Let’s take a look at some do’s and don’ts when it comes to posting replies with a backlink to your website.

DO’s:

  1. Use proper language, grammar, and jargon if applicable. The word “crowd” is here for a reason. If the community you’re targeting uses specific vocabulary, then use it as well. Proofread your comments and check for any grammar issues.
  2. Analyze the discussion before posting anything. Your comment should blend in with the rest of the thread. Make sure to read other user’s replies to get a better idea of the subject matter.
  3. Link back to your website in a natural way. Once you’ve written a solid comment, use this chance and include a backlink naturally. Use appropriate anchor text and don’t even try to do clickbait or push users to visit your website aggressively.

crowd marketing link building - dos - example

DON’Ts:

  1. Attempt to hide a backlink. This is black hat and will be punished by admins (or even by Google, if used excessively).
  2. Use software for mass posting. This doesn’t work anymore and will likely get you a Google penalty.
  3. Copy-paste the exact same answer template with your link. Context surrounding the link is important, so make sure it’s unique and sound.

Forum links: dofollow or nofollow?

“Nofollow links are useless” is probably one of the most common SEO misconceptions you will ever come across. In fact, having a natural mix of dofollow and nofollow links is very beneficial.

It is already confirmed that Google treats “nofollow” as a hint, that can potentially result in higher rankings, depending on the context, anchor text, and the referring domain. For example, everyone claims that Wikipedia backlinks are useful, although they’re always nofollow.

The main takeaway is

If you see that all the links posted in a particular forum have a nofollow tag, that’s not a reason to quit, as they might still be helpful for your ranking. Other than that, people click on the links regardless of their tag, so for traffic-generation that does not play a role at all. Just ensure that not all of the backlinks you build are nofollow, because this also doesn’t send Google the right signal.

Crowd marketing: So is it black hat or white hat?

The technique itself is entirely organic and white hat if you use it the right way. Basically, any SEO method can be turned into black hat if it’s abused.

For example, the same words can be said about outreach guest posting. If you genuinely reach out to website owners, propose interesting content, and use the opportunity to build a few links – that’s great and won’t ever get you penalized.

Now if you’re building a blog network solely for link-building purposes (for example, PBN), this is a black hat scheme that won’t go unnoticed.

The same logic can be applied here. If you’re writing genuine and helpful replies, that benefit the community and include relevant backlinks to your website, then you’re doing everything right. A well-carried crowd marketing campaign is not based on spam or volumes, quality is still key.

Don’t try to fool Google and use automated software and spam all night long, because that’s black hat and that’s punishable.

That’s great but looks like there are so many things to keep in mind…

Crowd marketing is definitely time-consuming! Let’s just summarize some of the things that you need to set up for a successful crowd marketing campaign:

  • You have to do a lot of research to find relevant forums and communities.
  • You have to check their metrics, traffic, and level of moderation.
  • You will have to create an account for each of them. In most cases, you’ll also have to build up some reputation before posting any links (or anything whatsoever).
  • In some cases, you will have to pay a membership fee to join an online community.
  • You have to search for niche-specific threads and write helpful replies for each of them.

As you can see, this does require a lot of time, resources, and dedication. That is why more often than not, SEO enthusiasts prefer to outsource this task to reputable link building services like Crowdo. There’s no one restricting you from doing this yourself, but soon you’ll find that it’s hard to do on a large scale.

In any case, don’t fall victim to shady backlink providers or freelancers, who are willing to do the job for cheap. You’ve just seen that doing it “the right way” is not easy, so if you see suspiciously low prices, that often means that either software was used or no research was carried along the way. Both of these will diminish your genuine SEO efforts.

Conclusion

We hope that you’ve learned everything there is to know about forum link building. If you would like to leave this job to professionals, you’re welcome to check what Crowdo has to offer with a 10% discount, exclusively for SEW readers!

If you want to find out more about forum link building, make sure you read their latest report here.

Andrei Cucleschin is a Marketing Lead at Crowdo. Besides writing content, he’s passionate about design, traveling, and coffee.

The post Crowd marketing: A link building method that only 2% use to rank higher on Google appeared first on Search Engine Watch.

Reblogged 1 year ago from www.searchenginewatch.com

Google services were down including Google Ads, Google Analytics, Search Console & more

Much of Google is offline, it is not just you. Google began restoring services at around 7:28am ET.

Please visit Search Engine Land for the full article.

Reblogged 1 year ago from feeds.searchengineland.com

How Redux Reducers Work

In this tutorial, we’re going to learn the concept of reducers and how they work, specifically in React applications. In order to understand and better use Redux, a solid understanding of reducers is essential. Reducers provide a way to update an application’s state using an action. It is an integral part of the Redux library.

This tutorial is for developers who want to learn more about Redux Reducers. An understanding of React and Redux would be beneficial. At the end of the tutorial, you should have a better understanding of the role Reducers play in Redux. We’ll be writing code demos and an application to better understand Reducers and how it affects the state in an application.

What Is A Reducer

A Reducer is a pure function that takes the state of an application and action as arguments and returns a new state. For example, an authentication reducer can take an initial state of an application in form of an empty object and an action that tells it that a user has logged in and returned a new application state with a logged-in user.

Pure functions are functions that do not have any side effects and will return the same results if the same arguments are passed in.

Below is an example of a pure function:

const add = (x, y) => x + y;

add(2, 5);

The example above returns a value based on the inputs, if you pass 2 and 5 then you’d always get 10, as long as it’s the same input nothing else affects the output you get, that’s an example of a pure function.

Below is an example of a reducer function that takes in a state and an action.

const initialState = {};
const cartReducer = (state = initialState, action) => {
  // Do something here
}

Let’s define the two parameters that a reducer takes in, state and action.

State

A state is the data that your component(s) is working with — it holds the data that a component requires and it dictates what a component renders. Once a state object changes, the component re-renders. If an application state is managed by Redux, then the reducer is where state changes happen.

Action

An action, is an object that contains the payload of information. They are the only source of information for the Redux store to be updated. Reducers update store based on the value of the action.type. Here we will define the action.type as ADD_TO_CART.

According to the official Redux documentation, actions are the only things that trigger changes in a Redux application, they contain the payload for changes to an application store. Actions are JavaScript objects that tell Redux the type of action to be performed, usually they’re defined as functions like the one below:

const action = {
  type: 'ADD_TO_CART',
  payload: {
    product: 'margarine',
    quantity: 4
  }
}

The code above is a typical payload value that contains what a user is sending and it will be used to update the state of the application. As you can see from above, the action object contains the type of action and a payload object that would be necessary for this particular action to be performed.

Updating State Using Reducers

To show how reducers work, let’s look at the number counter below:

const increaseAction = {
  type: 'INCREASE',
}; 

const decreaseAction = {
  type: 'DECREASE'
}; 


const countReducer = (state = 0, action) => {
  switch(action.type){
  case INCREASE: 
    return state + 1;

  case DECREASE : 
    return state -1;

  default: 
 return state;

  }
};

In the code above, increaseAction and decreaseAction are actions used in the reducer to determine what the state is updated to. Next, we have a reducer function called countReducer, which takes in an action and an initial state whose value is 0. If the value of action.type is INCREASE, we return a new state that is incremented by 1, else if it is DECREASE a new state that is decremented by 1 is returned. In cases where none of those conditions are meant, we return state.

Updating State Using Reducers: The Spread Operator

State can’t be directly changed, to create or update state, we can use the JavaScript spread operator to make sure we don’t change the value of the state directly but instead to return a new object that contains a state passed to it and the payload of the user.

const contactAction = {
  type: 'GET_CONTACT',
  payload: ['0801234567', '0901234567']
};

const initialState = {
  contacts: [],
  contact: {},
};

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_CONTACTS: 
      return {
        ...state,
        contacts: action.payload,
    };
  default: 
    return state;
  }

In the code above, we are using a spread operator to make sure we don’t change the state value directly, this way we can return a new object that is filled with the state that is passed to it and the payload that’s sent by the user. By using a spread operator, we can make sure that the state stays the same as we add all new items to it and also replace the contacts field in the state if it was present before.

Redux Reducers In Action — A Demo

To better understand Redux Reducers and how they work, we will be implementing a simple Movie details finder app, the code and working version can be found here on Codesandbox. To get started, go to your terminal and initialize a react app using the command below:

create-react-app movie-detail-finder

Once our project initialized, next let’s install the packages we’d need for our application.

npm i axios reactstrap react-redux redux redux-thunk

Once, the packages are installed, let’s start our development server using the command:

npm start

The above command should start our project development server in our browser. Next let’s open our project in our text editor of choice, inside our project src folder, delete the following files: App.css, App.test.js, serviceWorker.js and setupTests.js. Next, let’s delete all code that references the deleted files on our App.js.

For this project, we will be using Open Movie Database API to get our movie information, content and images for our application, here is a link to the API, you’d need to register and get access keys in order to use it for this application, Once you’re done, let’s proceed with our application by building components.

Building App Components

First, inside of our src folder in our project directory, create a folder called components and inside the folder, let’s create two folders called Movie and Searchbar, our component should look like the image below:

Building Movie Component

Let’s build the Movies component, which will outline the structure of the movie details we will be getting from our API. To do this, inside the Movies folder of our component, create a new file Movie.js, next create a class based component for the API results, let’s do that below.

import React, { Component } from 'react';
import { Card, CardImg, CardText, CardBody, ListGroup, ListGroupItem, Badge } from 'reactstrap';
import styles from './Movie.module.css';

class Movie extends Component{
    render(){
        if(this.props.movie){
            return (
                <div className={styles.Movie}>
                    <h3 className="text-center my-4">
                      Movie Name: {this.props.movie.Title}
                    </h3>
                    <Card className="text-primary bg-dark">
                        <CardImg className={styles.Img}
                          top src={this.props.movie.Poster} 
                          alt={this.props.movie.Title}/>
                        <CardBody>
                            <ListGroup className="bg-dark">
                              <ListGroupItem>
                                <Badge color="primary">Actors:</Badge>
                                  {this.props.movie.Actors}
                                  </ListGroupItem>
                          <ListGroupItem>
                            <Badge color="primary">Genre:</Badge>
                            {this.props.movie.Genre}
                          </ListGroupItem>
                          <ListGroupItem>
                            <Badge color="primary">Year:</Badge>
                            {this.props.movie.Year}
                          </ListGroupItem>
                          <ListGroupItem>
                            <Badge color="primary">Writer(s):</Badge> 
                            {this.props.movie.Writer}
                          </ListGroupItem>
                        <ListGroupItem>
                          <Badge color="primary">IMDB Rating:</Badge> 
                            {this.props.movie.imdbRating}/10
                        </ListGroupItem>
                    </ListGroup>
                      <CardText className="mt-3 text-white">
                        <Badge color="secondary">Plot:</Badge>
                          {this.props.movie.Plot}
                        </CardText>
                      </CardBody>
                    </Card>
                </div>
            )
        }
        return null
    }
}
export default Movie;

In the code above, Using components from the package reactstrap, you can check out the documentation here. We built a Card component that includes the movie name, Image, genre, actor, year, movie writer, rating, and plot. To make it easier to pass data from this component, we built data to be as props to other components. Next, let’s build our Searchbar component.

Building Our Searchbar Component

Our Searchbar component will feature a search bar and a button component for searching movie components, let’s do this below:

import React from 'react';
import styles from './Searchbar.module.css';
import { connect } from 'react-redux';
import { fetchMovie } from '../../actions';
import Movie from '../Movie/Movie';

class Searchbar extends React.Component{
render(){
        return(
            <div className={styles.Form}>
                <div>
                    <form onSubmit={this.formHandler}>
                        <input 
                            type="text" 
                            placeholder="Movie Title" 
                            onChange={e => this.setState({title: e.target.value})}
                            value={this.state.title}/>
                        <button type="submit">Search</button>
                    </form>
                </div>
                <Movie movie={this.props.movie}/>
            </div>
        )
    }
}

In the code above, we are importing connect from react-redux which is used to connect a React component to the Redux store, provides the component with information from the store and also provides functions used to dispatch actions to the store. Next, we imported the Movie component and a function fetchMovie from actions.

Next, we have a form tag with an input box for entering our movie titles, using the setState hook from React, we added an onChange event and value that will set the state of title to the value entered in the input box. We have a button tag to search for movie titles and using the Movie component that we imported, we passed the properties of the component as props to the result of the search.

Next for us is to write a function to submit our movie title to the API in order to send results to us, we also need to set the initial state of the application. let’s do that below.

class Searchbar extends React.Component{

    state = {
        title: ''
    }
    formHandler = (event) => {
        event.preventDefault();
        this.props.fetchMovie(this.state.title);
        this.setState({title: ''});
    }

Here, we set the initial state of the application to empty strings, we created a function formHandler that takes in an event parameter and passes the fetchMovie function from action and setting the title as the new state of the application. To complete our application, let’s export this component using the connect property from react-redux, to do this we’d use the react redux mapToStateProps property to select the part of the data our component would need, you can learn more about mapToStateProps here.

const mapStateToProps = (state) => {
    return { movie: state.movie }
}
export default connect(mapStateToProps, { fetchMovie })(Searchbar)

Let’s add styles to our form by creating a file Searchbar.module.css and adding the styles below:

.Form{
  margin: 3rem auto;
  width: 80%;
  height: 100%;
}
input{
  display: block;
  height: 45px;
  border: none;
  width: 100%;
  border-radius: 0.5rem;
  outline: none;
  padding: 0 1rem;
}
input:focus, select:focus{
  border: 2px rgb(16, 204, 179) solid;
}

.Form button{
  display: block;
  background: rgb(16, 204, 179);
  padding: 0.7rem;
  border-radius: 0.5rem;
  width: 20%;
  margin-top: 0.7rem;
  color: #FFF;
  border: none;
  text-decoration: none;
  transition: all 0.5s;
}
button:hover{
  opacity: 0.6;
}
@media(max-width: 700px){
  input{
      height: 40px;
      padding: 0 1rem;
  }
  .Form button{
      width: 40%;
      padding: 0.6rem;
  }
}

Once we’ve done the above, our search bar component should look similar to the image below:

Creating Actions For Application

In this component, we will be setting up Redux actions for our application, First, inside the src directory, create a folder named actions and inside the folder, we’d create an index.js file. Here we’d create a function fetchMovie that takes in a title parameter, and fetches movie from the API using Axios. Let’s do this below:

import axios from 'axios';

export const fetchMovie = (title) =>
    async (dispatch) => {
        const response = await 
          axios.get(
            https://cors-anywhere.herokuapp.com/http://www.omdbapi.com/?t=${title}&apikey=APIKEY);
        dispatch({
            type: 'FETCH_MOVIE',
            payload: response.data
        })
    }

In the code above, we imported axios and created a function called fetchMovie which takes in a title parameter by using async/await so that we can make a request to the API server. We have a dispatch function that dispatches to the Redux the action object that is passed to it. From what we have above, we’re dispatching an action with the type FETCH_MOVIE and the payload that contains the response we got from the API.

NOTE: The apikey in the request will be replaced with your own apikey after registering at OmdbAPI.

Creating App Reducers

In this section, we are going to create reducers for our application.


const fetchMovieReducer = (state = null, action) => {
    switch(action.type){
        case 'FETCH_MOVIE':
            return action.payload;
        default:
            return state;
    }
}
const rootReducer = (state, action) => {
    return { 
        movie: fetchMovieReducer(state, action)
    }
}
export default rootReducer;

In the code above, we created a fetchMovieReducer that takes in a default state of null and an action parameter, using a switch operator, for case FETCH_MOVIE we will return the value of the action.payload which is the movie we got from the API. If the action we tried performing isn’t in the reducer, then we return our default state.

Next, we created a rootReducer function that will accept the current state and an action as input and returns the fetchMovieReducer.

Putting It Together

In this section, we’d finish our app by creating our redux store in the index.js, let’s do that below:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import reducers from './reducers';

const store = createStore(reducers, applyMiddleware(thunk))
ReactDOM.render(
    <Provider store={store}>
        <>
          <App/>
        </>
    </Provider>,
    document.getElementById('root')
)

In the code above, we created the application store using the createStore method by passing the reducer we created and a middleware. Middlewares are addons that allow us to enhance the functionalities of Redux. Here we are making use of the Redux Thunk middleware using applyMiddleware. The Redux Thunk middleware is necessary for our store to do asynchronous updates. This is needed because by default, Redux updates the store synchronously.

To make sure our application knows the exact store to use, we wrapped our application in a Provider component and passed the store as a prop, by doing this, other components in our application can connect and share information with the store.

Let’s add a bit of style to our index.css file.

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body{
  background: rgb(15, 10, 34);
  color: #FFF;
  height: 100vh;
  max-width: 100%;
}

Rendering And Testing A Movie Detail Finder

In this section, we are going to conclude our application by rendering our application in our App.js, to do this, let’s create a class-based component named App and initialize our Searchbar and input field.

import React from 'react';
import Searchbar from './components/Searchbar/Searchbar';
import styles from './App.module.css';
class App extends React.Component{

    render(){
        return(
            <div className={styles.App}>
                <h1 className={styles.Title}>Movies Search App</h1>
                <Searchbar/>
            </div>

        )
    }
}
export default App;

Here, we created an App class based component with a h1 that says Movie Search App and added our Searchbar component. Our application should look like the image below:

A working demo is available on Codesandbox.

Conclusion

Reducers are an important part of Redux state management, with reducers we can write pure functions to update specific areas of our Redux applications without side effects. We’ve learned the basics of Redux reducers, their uses, and the core concept of reducers, state, and arguments.

You can take this further by seeing the documentation on Redux reducers here. You can take this further and build more on Redux reducers, let me know what you build.

Resources

Reblogged 1 year ago from smashingmagazine.com

Smashing Podcast Episode 31 With Eve Porcello: What Is GraphQL?

In this episode, we’re talking about GraphQL. What is it, and how does solve some common API problems? I spoke with expert Eve Porcello to find out.

Show Notes

Weekly Update

Transcript

Drew McLellan: She’s a software engineer, instructor, author, and co-founder of training and curriculum development company, Moon Highway. Her career started writing technical specifications and creating UX designs for web projects. Since starting Moon Highway in 2012, she’s created video content for egghead.io and LinkedIn Learning, and has co-authored the books Learning React and Learning GraphQL for O’Reilly’s Media.

Drew: She’s also a frequent conference speaker, and has presented at conferences including React Rally, GraphQL Summit, and OSCON. So we know she’s an expert in GraphQL, but did you know she once taught a polar bear to play chess? My smashing friends, please welcome Eve Porcello.

Drew: Hi Eve, how are you?

Eve Porcello: I’m smashing.

Drew: As I mentioned there, you’re very much an educator in things like JavaScript and React, but I wanted to talk to you today about one of your other specialist areas, GraphQL. Many of us will have heard of GraphQL in some capacity, but might not be completely sure what it is, or what it does, and in particular, what sort of problem it solves in the web stack.

Drew: So set the stage for us, if you will, if I’m a front end developer, where does GraphQL slot into the ecosystem and what function does it perform for me?

Eve: Yeah. GraphQL kind of fits between the front end and the backend. It’s kind of living in the middle between the two and gives a lot of benefits to front end developers and back end developers.

Eve: If you’re a front end developer, you can define all of your front ends data requirements. So if you have a big list of React components, for example, you could write a query. And that’s going to define all of the fields that you would need to populate the data for that page.

Eve: Now with the backend piece, it’s really own, because we can collect a lot of data from a lot of different sources. So we have data in REST APIs, and databases, and all these different places. And GraphQL provides us this nice little orchestration layer to really make sense of the chaos of where all of our data is. So it’s a really useful for kind of everybody all over the stack.

Drew: So it’s basically an API based technology, isn’t it? It sits between your front end and your back end and provide some sort of API, is that correct?

Eve: Yeah, that’s exactly right. Exactly.

Drew: I think, over the last decade, the gold standard for APIs has been rest. So if you have a client side app and you need to populate it with data from the backend, you would build a REST API endpoint and you’d query that. So where does that model fall down? And when might we need GraphQL to come in and solve that for us?

Eve: Well, the problem that GraphQL really helps us with, kind of the golden problem, the golden solution, I guess, that GraphQL provides is that with REST we’re over fetching a lot of data. So if I have slash users or slash products, that’s going to give me back all of the data every time I hit route.

Eve: With GraphQL, we can be a little bit pickier about what data we want. So if I only need four fields from an object that has a hundred, I’m going to be able to really pinpoint those fields and not have to load data into, or load all of that data I should say, into your device, because that’s a lot of extra legwork, for your phone especially.

Drew: I’ve seen and worked with REST APIs in the past that have an optional field where you can pass in a list of the data that you want back, or you can augment what comes back with extra things. And so I guess that’s identifying this problem, isn’t it? That’s saying, you don’t always want the same data back every time. So is it that GraphQL formalizes that approach of allowing the front end to specify what the backend is going to return, in terms of data?

Eve: Yeah, exactly. So your query then becomes how you ask, how you filter, how you grasp for any sort of information from anywhere.

Eve: I also think it’s important to note that we don’t have to tear down all of our REST APIs in order to work with GraphQL really successfully. A lot of the most successful implementations of GraphQL I’ve seen out there, it’s wrappers around REST APIs. And the GraphQL query really gives you a way to think about what data you need. And then maybe some of your data comes from our users and products, examples, some of the data comes from rest, some of it comes from a database.

Drew: I guess the familiar scenario is, you might have an endpoint on your website that returns information about a user to display the header. It might give you their username and their avatar. And you cull that on every page and populate the data, but then you find somewhere else in your app you need to display their full name.

Drew: So you add that to the endpoint and it starts returning that. And then you do your account management section, and you need like their mailing address. So that gets returned by that endpoint as well.

Drew: And before you know it, that endpoint is returning a whole heavy payload that costs quite a lot on the backend to put together, and obviously a lot to download.

Drew: And that’s been culled on every single page just to show an avatar. So I guess that’s the sort of problem that grows over time, that was so easy to fall into, particularly in big teams, that GraphQL, it’s on top of that problem. It knows how to solve that, and it’s designed around solving that.

Eve: Exactly. And yeah, I think that whole idea of a GraphQL Schema, I think is a really, it’s kind of less talked about than the query language part of GraphQL. But I really feel like the Schema in particular gives us this nice type system for API.

Eve: So anybody on the team, managers, front end developers, back end developers, anybody who is really dealing with data can come together, coalesce around what data we actually want to serve up on this API, and then everyone knows what that source of truth is, they can go build their own parts of the app based on that.

Eve: So there’s some tricky Schema management things that come up with that too. But as far as moving from microservices back to monoliths, we’re sort of doing that, but getting all of the benefits we like out of microservices still.

Drew: And do I understand correctly that the typical way of setting up a GraphQL system is that you’d have basically one route, which is the endpoint that you send all your queries to so you’re not having to… Often one of the most difficult things is working out what to name, and what the path should be that this particular query should be at. It’s returning users and products, should it be it slash users something, or slash product something?

Drew: With GraphQL you just have one endpoint that you just fire your queries to and you get back an appropriate response.

Eve: Exactly. Yeah. It’s a single endpoint. I guess, you still are dealing with problems of naming because you’re naming everything in the Schema. But as far as, I feel like a lot of companies who have made big bets on microservices, everyone’s like, what endpoints do we have? Where are they? How are they documented? And with GraphQL, we have one place, one kind of dictionary to look up anything that we want to find out about how the API works.

Drew: So, I’m very familiar with other query languages, like SQL is an obvious example of a query language that a lot of web developers will know. And the queries in that take the form of almost like a command. It’s a text string, isn’t it, Select this from that, where, whatever. What format do the queries take with GraphQL?

Eve: It’s still a tech string, but it doesn’t define where that logic comes from. And a lot of the logic is moved back to the server. So the GraphQL server, the GraphQL API is really responsible for saying, “Go get this data from where it is, filter it based on these parameters.”

Eve: But in the query language, it’s very field oriented. So we just add fields for anything that we want to retrieve. We can put filters on those queries, of course, too. But I think it’s a little less direct about where that information comes from. A lot of the functionality is built into the server.

Drew: So you can mix and match in a query. You can make a request that brings back lots of different types of data in one request. Is that right?

Eve: Yeah, that’s absolutely right. So you could send a query for as many fields as your server would allow, and bring back all sorts of nested data. But that’s really how it works, we connect different types on fields. So I guess we’ll recycle my users and products idea, but the user might have a products field that returns a list of products. All of those are associated with other types as well. So as deeply nested as we want the query to go, we can.

Drew: So does that mean to retrieve the data for a typical view in your web application that might have all sorts of things going on, that you can just make one request to the backend and get that all in one go without needing to make different queries to different endpoints, because it’s all just one thing?

Eve: Yeah. That’s exactly the whole goal, is just a single query, define every field that you want, and then return it in one response.

Drew: And the queries are Jason based? Is that right?

Eve: … Turn it in one response.

Drew: And the queries are JSON based, is that right?

Eve: The query itself is a text string, but it typically returns JSON data. So if I have the fields, then my JSON response matches exactly, and so it’s really clear what you’re getting when you send that query, because the data response looks exactly the same.

Drew: A lot of the queries it seems like are for almost like bare objects, like a customer or a product. Is there a way to specify more complex queries where business logic is controlled at the backend? Say I want to get a list of teams for a user, but only where that user is an admin of a team and where the team plan hasn’t expired, and all those sorts of real constraints that we face in everyday web application development. Can that be achieved with GraphQL?

Eve: Absolutely. So that’s the real exciting, powerful thing about GraphQL is, you can move a lot of that logic to the server. If you had a complex query, some really specific type of user that you wanted to get, all you’d need to do in the Schema is say, “Get complicated user”, and then on the server, there would be a function where you could write all of the logic in whatever language you wanted to. JavaScript is kind of the most popular GraphQL implementation language, but you don’t have to use that at all. So Python, Go, C++, whatever you want to use, you can build a GraphQL server with that. But yeah, you can define as complex a query as you’d like to.

Drew: And I guess that enables you to encapsulate a lot of business logic then in new types of objects. Is that fair? You know, you set up a complicated user and then you don’t need to think what a complicated user is, but you can just keep using that complicated user and know that the business logic is implemented on that. Is that right?

Eve: That’s exactly right. So I think this is really nice for front end folks because they can start to prototype based on that. And then the backend team could go implement those functions to make that work. And then there’s kind of this shared understanding for what that type actually is and who they are, and, “What are the fields on that type?” And everything can be handled by wherever in the stack GraphQL is working. And that’s why it’s not really a front end or a back end technology. It’s really kind of both, and neither.

Drew: It sounds like it’s sort of formalizing the API and the relationship between front end and backend, so everybody’s getting a predictable interface that is standardized.

Eve: Exactly.

Drew: Which I guess in organizations where the front end and the backend are owned by different teams, which isn’t at all uncommon, I guess this approach also enables changes to be made, say, on the front end, it might require different data, without needing somebody who works on the backend to make the changes that correspond to that. You’ve still got this almost infinitely customizable API without requiring any work to be done to change it if you need new data.

Eve: Yeah, exactly right.

Drew: So is the GraphQL server responsible for formatting the response, or do you need to do that in your server side logic?

Eve: So the GraphQL server defines two things. It defines the Schema itself that lives on the server, and then it defines the resolver functions. Those are functions that go get the data from wherever it is. So if I have a REST API that I’m wrapping with GraphQL, the resolver would fetch from that API, transform the data however it needed to be, and then return it to the client in that function. You can use any sort of database functions you’d like to on that server as well. So if you have data in a bunch of different places, this is a really nice cohesive spot to put all of that data in and to kind of design all the logic around, “Where’s that data coming? How do we want to transform it?”

Drew: The client says, “I want a complex user”, the server receives that in a query and could say, “Right, I’m going to look up the complex user resolver.” Is that right?

Eve: Mm-hmm (affirmative).

Drew: Which is the function, and then you write your logic that your backend team, or whoever writes the logic inside that function, to do whatever is necessary to return a complex user.

Eve: Yeah, exactly.

Drew: So that could be calling other APIs, it could be querying a database, it could be looking stuff up in cache, or pretty much anything.

Eve: Pretty much anything. And then, as long as that return from the function matches the requirements of the Schema, matches what fields, what types, were returning there, then everything will work nice and harmoniously.

Drew: I guess it gives you a consistent response format across your entire API just by default. You don’t have to design what that looks like. You just get a consistent result.

Eve: Yeah, exactly.

Drew: I think that could be quite a win really, because it can be really difficult to maintain consistency across a big range of API end points, especially in larger teams. Different people are working on different things. Unless you have quite strict governance in place, it can get really complex really quickly, can’t it?

Eve: Yeah, absolutely. And I think that Schema is just such a nice little document to describe everything. You get the automatic benefit of being able to see all of the fields in that Schema whenever you’re trying to send queries to it, because you can send introspection queries and there’s all sorts of nice tools for that, like GraphQL and GraphQL Playground, little tools that you can use to interact with the API’s data.

Eve: But also, if you’ve ever played around with Postman, like to ping a REST API, a lot of those, the documentation doesn’t really exist or it’s tough to find, or things like that. GraphQL really gives you that nice cohesive layer to describe everything that might be part of that API.

Drew: Practically, how do things work on the server side? I mean, I guess you need to run a GraphQL service as part of your infrastructure, but what form does that take? Is it an entire server running on its own port? Or is it just like a library you integrate into your existing Express or Apache or whatever with a route that resolves to that service? How do you implement it?

Eve: Yeah, it’s an actual server. So kind of the most popular GraphQL implementations are Node.js servers. When GraphQL as a spec was released, the team released this reference implementation in JavaScript, kind of a Node server that served as the guidelines for all these other ones who have popped up. But yeah, you can run these servers on their own instances. You can put them on Lambda. So there’s Apollo Server Express, there’s Apollo Server Lambda; all sorts of different types of implementations that you can use to actually run this thing.

Drew: So you mentioned briefly before the concept of a Schema that the server has.

Eve: Yeah.

Drew: That gives you the ability to describe your types more strictly than just, you know, mapping a name to a resolver. There’s more involved there, is there?

Eve: Yeah. There’s a full language. So I’ve referenced the spec and I didn’t describe what it is. GraphQL itself is a spec that describes the query language and the Schema definition language. So it has its own syntax. It has its own rules for defining these types.

Eve: When you’re using the Schema definition language, you basically use all of the features of that language to think about, what are the types that are part of the API? It’s also where you define the queries, the mutations, which are the verbs, like the actions, create account login, things like that. And even GraphQL subscriptions, which are another cool thing, real time GraphQL that you can define right there in the Schema.

Eve: So yeah, the Schema really is super important. And I think that it gives us this nice type enforcement across our full Stack application, because as soon as you start to deviate from those fields and from those types, you start to see errors, which is, in that case, good, because you’re following the rules of the Schema.

Drew: Is there any crossover between that and TypeScript? Is there a sort of synergy between the two there?

Eve: Absolutely. So if you’re a person who talks about GraphQL a lot, sometimes people will tell you that it’s bad, and they’ll come up to you publicly, when you could do that, and talk about how GraphQL is no good. But a lot of times they skip out on the cool stuff you get from types. So as far as synergy with TypeScript goes, absolutely, you can auto-generate types for your front end application using the types from the Schema. So that’s a huge win because you can not only generate it the first time, which gives you great interoperability with your front end application, but also, as things change, you can regenerate types and then build to reflect those changes. So yeah, I think those things fit really nicely together as types start to be kind of the defacto rule.

Eve: … to be kind of the defacto rule in JavaScript, they fit nicely together.

Drew: It seems to be a sort of ongoing theme with the way that TypeScript has been designed … that’s not TypeScript, sorry. GraphQL has been designed that there’s a lot of about formalizing the interaction between the front end and the back end. And it’s coming as a solution in between the just creates consistency and a formalization of what so far has been otherwise a fairly scrappy experience with rest for a lot of people. One thing that we always have to keep in mind when writing client-side apps is that the code is subject to inspection and potentially modification. And having an API where the client can just request data could be dangerous. Now, if you can specify what fields you want, maybe that could be dangerous. Where in the sort of the whole stack, would you deal with the authorization of users and making sure that the business rules around your data enforced?

Eve: You would deal with that all on the server. So, that could happen in many different ways. You don’t have to use one off strategy, but your resolvers will handle your authorization. So that could mean wrapping an existing off REST API, like a service like Auth0 or something you’ve built on your own. That could mean interacting with an OAuth, like GitHub or Facebook or Google login, those types of things that involves kind of passing tokens back and forth with resolvers. But oftentimes that will be built directly into the Schema. So the Schema will say, I don’t know, we’ll create a login mutation. And then I send that mutation with my credentials and then on the server, all of those credentials are verified. So the client doesn’t have to worry so much, maybe a little bit of passing tokens and things like that. But most of that is just built into the server.

Drew: So essentially, that doesn’t really change compared to how we’re building rest endpoints at the moment. Rest as a technology, well, it doesn’t really deal with authorization either and we have middleware and things on the server that deals with it. And it’s just the same with GraphQL. You just deal with it. Are there any conventions in GraphQL community for doing that? Are there common approaches or is it all over the place for how people choose to implement it?

Eve: It’s honestly all over the place. I think most times you’ll see folks building off into the Schema and by that I mean, representing those types and authorized users versus regular users building those types into the Schema itself. But you’ll also see a lot of folks using third-party solutions. I mentioned Auth0. A lot of folks will kind of offload their authorization on to companies who are more focused on it, particularly smaller companies, startups, things like that. But you’ll also see bigger companies starting to create solutions for this. So AWS, Amazon has AppSync, which is their flavor of GraphQL, and they have author rolls built directly into AppSync. And that’s kind of cool just to be able to, I don’t know, not have to worry about all of that stuff or at least provide an interface for working with that. So a lot of these ecosystem tools have, I think authorization is such a big topic in GraphQL. They’ve seen kind of the need, the demand for auth solutions and standard approaches to handling auth on the graph.

Drew: I guess there’s hardly a, an implementation out there that doesn’t need some sort of authorization. So yeah, it’s going to be a fairly common requirement. We’re all sort of increasingly building componentized applications, particularly when we’re using things React and View and what have you. And the principle of loose coupling leaves us with lots of components that don’t necessarily know what else is running on the page around them. Is there a danger as a result of that, you could end up with lots of components querying for the same data and making multiple requests? Or is it just an architectural problem in your app that you need to solve for that? Are there sort of well-trodden solutions for dealing with that?

Eve: Well, I think because GraphQL for the most part, not 100% of the solutions, but almost every GraphQL query is sent over HTTP. So if you want to track down where those multiple requests are happening, it’s probably a fairly familiar problem to folks who are using rest data for their applications. So there are some tools like Paulo Client Dev Tools and Urkel Dev Tools for front end developers who are like, “What’s going on? Which queries are on this page?” That gives you really clear insights into what’s happening. There’s kind of several schools of thought with that. Do we create one big, huge query for all of the data for the page? Or do we create smaller queries to load data for different parts of the app? Both as you might imagine, they have their own drawbacks, just because if you have a big query, you’re waiting for more fields.

Eve: If you have smaller queries, there may be collisions between what data you’re requiring. But I think, and not to go off on too much of a tangent, but I’m there already. So the there’s something called the Deferred Directive that’s coming to the GraphQL spec and the Deferred Directive is going to help with kind of secondarily loading content. So let’s say you have some content at the top of the page, the super important content that you want to load first. If you add that to your query and then any subsequent fields get the deferred directive on that. It’s just a little decorator that you would add to a field, that will then say, “All right, load the important data first, then hold up and load the second data second.” And it kind of gives you this, it’s the appearance of kind of streaming data to your front end, so that there’s perceived performance, there’s interactivity. People are seeing data right away versus waiting for every single field to load for the page, which yeah, it could be a problem.

Drew: Yeah. I guess that enables you to architect pages where everything that’s … we don’t like to talk too much about the viewport, but it is everything above the fold, you could prioritize, have that load in and then secondarily load in everything sort of further down. So, we’ve talked a lot about querying data. One of the main jobs of an API is sending new and modified data back to the server for persistence. You mentioned briefly mutations earlier. That’s the terminology that’s GraphQL uses for writing data back to the server?

Eve: Exactly. So any sort of changes we want to make to the data, anything we want to write back to the server, those are mutations, and those are all just like queries, they’re named operations that live on the server. So you can think about what are all the things we want our users to be able to do? Represent those with mutations. And then again on the server, write all the functions that make that stuff work.

Drew: And is that just as simple as querying for data? Calling a mutation is just as easy?

Eve: Yeah. It’s part of the query language. It looks pretty much identical. The only difference is, well, I guess queries take in filters. So mutations taken what looked like filters in the query itself. But those are responsible for actually changing data. An email and a password might get sent with a mutation, and then the server collects that and then uses that to authorize the user.

Drew: So, just as before, you’re creating a resolver on the backend to deal with that and to do whatever needs to be done. One common occurrence when writing data is that you want to commit your changes and then re-query to get the sort of current state of it. Does GraphQL have a good workflow for that?

Eve: It sort of lives in the mutation itself. So, a lot times when creating your Schema you’ll create the mutation operation. I’ll stick with log-in, takes in the email and the password. And the mutation itself returned something. So it could return something as simple as a Boolean, this went well, or this went badly, or it could return an actual type. So oftentimes you’ll see the mutation like the log-in mutation, maybe it returns a user. So you get all the information about the user once they’re logged in. Or you can create a custom object type that gives you that user plus what time the user logged in, and maybe a little more metadata about that transaction in the return object. So again, it’s kind of up to you to design that, but that pattern is really baked into GraphQL.

Drew: This all sounds pretty great, but every technical choice involves trade-offs. What are the downsides of using GraphQL? Are there any scenarios where it’d be a really poor choice?

Eve: I think that the place where a GraphQL might struggle is creating a one-to-one map of-

Eve: … struggle is creating a one-to-one map of tabular data. So let’s say you have, I don’t know, think a database table with all sorts of different fields and, I don’t know, thousands of fields on a specific type, things like that, that type of data can be represented nicely with GraphQL, but sometimes when you run a process to generate a Schema on that data, you’re left with, in a Schema, the same problems that you had in the database, which is maybe too much data that goes beyond what the client actually requires. So I think those places, they’re potentially problems. I’ve talked to folks who have auto-generated Schemas based on their data and it’s become a million line long Schema or something like that, just thousands and thousands of lines of Schema code. And that’s where it becomes a little tricky, like how useful is this as a human readable document?

Eve: Yeah. So any sort of situation where you’re dealing with a client, it is a really nice fit as far as modeling every different type of data, it becomes a little tricky if your data sources too large.

Drew: So it sounds like anywhere where you’re going to carefully curate the responses in the fields and do it more by hand, you can get really powerful results. But if you’re auto-generating stuff because you’ve just got a massive Schema, then maybe it becomes a little unwieldy.

Eve: Yeah. And I think people are listening and disagreeing with me on that because there are good tools for that as well. But I think kind of the place where GraphQL really shines is that step of abstracting logic to the server, giving front end developers the freedom to define their components or their front ends data requirements, and really managing the Schema as a team.

Drew: Is there anything sort of built into the query language to deal with pagination of results, or is that down to a custom implementation as needed?

Eve: Yeah. Pagination, you would build first into the Schema, so you could define pagination for that. There’s a lot of guidelines that have sort of emerged in the community. A good example to look at if you’re newer to GraphQL or not, I look at this all the time, is the GitHub GraphQL API. They’ve basically recreated their API for v4 of their public facing API using GraphQL. So that’s a good spot to kind of look at how is a actual big company using this at scale. A lot of folks have big APIs running, but they don’t make it public to everybody. So pagination is built into that API really nicely and you can return, I don’t know, the first 50 repositories that you’ve ever created, or you can also use cursor based pagination for returning records based on ideas in your data. So cursor based pagination and kind of positional pagination like first, last records, that’s usually how people approach that, but there’s many techniques.

Drew: Are there any big got yous we should know going into using GraphQL? Say I’m about to deploy a new GraphQL installation for my organization, we’re going to build all our new API endpoints using GraphQL going forward. What should I know? Is there anything lurking in the bushes?

Eve: Lurking in the bushes, always with technology, right? I think one of the things that isn’t built into GraphQL, but can be implemented without too much hassle is API security. So for example, you mentioned if I have a huge query, we talked about this with authorization, but it’s also scary to open up an API where someone could just send a huge nested query, friends of friends, friends of friends, friends of friends, down and down the chain. And then you’re basically allowing people to DDoS you with these huge queries. So there’s things that you can set up on the server to limit query depth and query complexity. You can put queries on a safe list. So maybe your front ends, you know what they all are and it’s not a public API. So you only want to let certain queries come over the wire to you. So I would say before rolling that out, that is definitely a possible got you with the GraphQL.

Drew: You do a lot of instruction and training around GraphQL, and you’ve co-written the O’Reilly ’animal’ book with Alex Banks called Learning GraphQL. But you’ve got something new that you’re launching early in 2021, is that right?

Eve: That’s right. So I have been collaborating with egghead.io to create a full stack GraphQL video course. We’re going to build an API and front end for a summer camp, so everything is summer camp themed. And yeah, we’re just going to get into how to work with Apollo server, Apollo client. We will talk about scaling GraphQL APIs with Apollo Federation. We’ll talk about authorization strategies and all sorts of different things. So it’s just kind of collecting the things that I’ve learned from teaching over the past, I don’t know, three or four years GraphQL and putting it into one spot.

Drew: So it’s a video course that… Is it all just self-directed, you can just work your way through at your own pace?

Eve: Yeah, exactly. So it’s a big hefty course so you can work through it at your own pace. Absolutely.

Drew: Oh, that sounds really good. And it’s graphqlworkshop.com, is that right?

Eve: Graphqlworkshop.com, exactly.

Drew: And I’m looking forward to seeing that released because I think that’s something that I might need. So I’ve been learning all about GraphQL. What have you been learning about lately?

Eve: I’ve also been looking into Rust lately. So I’ve been building a lot of Rust Hello Worlds, and figuring out what that is. I don’t know if I know what that is yet, but I have been having fun tinkering around with it.

Drew: If you dear listener, would like to hear more from Eve, you can find her on Twitter where she’s @eveporcello, and you can find out about her work at moonhighway.com. Her GraphQL workshop, discover your path through the GraphQL wilderness, is coming out early in 2021 and can be found at graphqlworkshop.com. Thanks for joining us today, Eve. Do you have any parting words?

Eve: Parting words, have fun with GraphQL, take the plunge, you’ll enjoy it, and thanks so much for having me. I appreciate it.

Reblogged 1 year ago from smashingmagazine.com

The expansion of People Also Ask in the search results

PAAs now appear in 9% of brand knowledge panels. Here’s how they’re different and why you need to optimize answers for brand-focused questions.

Please visit Search Engine Land for the full article.

Reblogged 1 year ago from feeds.searchengineland.com

Google Maps local listing now showing web search results

As you scroll through the local listings in Google Maps, Google may show you web results at the bottom.

Please visit Search Engine Land for the full article.

Reblogged 1 year ago from feeds.searchengineland.com