How to Switch-Off After Work and Boost Your Productivity

Post pobrano z: How to Switch-Off After Work and Boost Your Productivity

In the modern working world, people wear the overworking habits like a badge of honor, however, your knack for staying in the office until 9pm and answering your emails late into the night does not make you a good employee. Research has shown that a happy employee is an efficient employee, and those that have perfected the art of a suitable work-life balance are 28% more productive than those who haven’t. A willingness to work all hours of the day and not draw a sharp distinction between your work life and your personal life can have a detrimental effect on your wellbeing, and impact your performance in a negative way.

The ideal way to stay productive is to make the most of your time in the office and to draw a line between your time in the workplace and your time outside of it. Here’s your brief guide to switching-off after the working day ends, and boosting your productivity as a result.

Relaxing by Simon Migaj

9 to 5 means 9 to 5

The most important way to keep a good line between work and personal life is to ensure you have a disciplined schedule and a firm cut-off point for when it is no longer acceptable to continue working. If you have standard US office hours of 9am to 5pm, then those are the hours you should be working, no more. Set a timer on your email account to make sure notifications are switched-off once you leave the office, and be firm with colleagues about when it is acceptable to discuss work. The important thing is to be assertive.

How to Transition from Work to Play

Switching-off after a busy day at work is easier said than done, so make sure that you have some tried and tested activities in place to do once you clock out, in order to ease your brain into a post-work mode. The best time to do this is during your commute home or during your first hour after work, and the best activity is a solitary one. You could try reading a book, or better yet, playing some online games to ease your mind. With the accessibility of online games and casino games, in particular, being more accessible than ever, simply popping open your laptop on the bus ride home and playing some table games at William Hill is an example of an easy way to erase the stresses of the day and get into a post-work state of mind. Working your post-work activity into your daily schedule is key, so make sure to keep at it until it feels like second nature.

Maintaining a Healthy Work-Life Balance

The internet giant Google has invested serious resources into establishing a work-life balance for their employees and has found that the happiest and most useful workers are the ones that can maintain that balance effortlessly. It usually takes a few weeks to be able to get into the habit of forgetting about work once your paid hours are over, so commitment and plenty of tried and tested activities are the ultimate way to go.

With hard work and exhaustion acquiring a position as a kind of status symbol, it’s more important than ever to remember that your real life is more important and that you should work to live, rather than living to work.

Featured image by Jeremy Bishop

Samsung: Fear

Post pobrano z: Samsung: Fear

Film
Samsung

Samsung IT encourages everyone to break through their own fears and execute what they think it’s beyond their capabilities. With the collaboration with the producer of ‘Home sweet home’, a Thai online game that creates phenomenon in an international platform, tells the concept of creating game that is not only step over the fear from social perspectives, but also using fear to represents Thai culture & belief internationally.

Advertising Agency:mInteraction, Bangkok, Thailand
General Manager:Jirat Arinrith
Executive Creative Director:Puripong Limwanatipong
Creative Director:Buncharith Saovapichard
Art Director:Sitthisak Sirinorakul
Copywriter:Varissara Vongsakul
Client Service Director:Peeraya Leelachart
Account Director:Prapatsorn Mahawana
Account Manager:Chutima Buranateerakij
Account Executive:Kornkamol Trreeyong
Production Director:Sukontha Jantawong
Production House:MeOur Production

Amnesty International: China’s Real Estate Prices

Post pobrano z: Amnesty International: China’s Real Estate Prices

Film
Amnesty International

Serviceplan Belgium created an Architectural Model with a difference, in order to promote an Amnesty International petition supporting human rights campaigner Ni Yulan, and drawing attention to the millions of Chinese forced out of their homes to make way for real estate.

Advertising Agency:Serviceplan, Belgium
Executive Creative Directors:Naim Baddich, Merel Van Den Broeck
Art Director:Marc Thomasset
Copywriter:Nathalie Strybos
Account Director:Anton Roef
Production:Veerle Guiljam
3D Artwork:Gonzalo R. Checa
Graphic:Denise Hermo, Bart Leijnen, Stéphane Melnik, Sergio Menendez
Motion Design:Denise Hermo, Bart Leijnen, Stéphane Melnik, Sergio Menendez

The Aguda: #ProudStrikers

Post pobrano z: The Aguda: #ProudStrikers

Online
The Aguda

Advertising Agency:BBR Saatchi & Saatchi, Tel Aviv, Israel
Chief Executive Officer:Yossi Lubaton
Chief Creative Officer:Idan Regev
Digital Creative Director:Idan Kligerman
Art Director:Noa Navot
Copywriters:Kobi Lavi, Avner Ressel, Omri Zidon
Marcom Director:Eva Hasson
Vp:Ben Muskal
Client Services:Ben Muskal
Account Executive:Hila Kirma
Vp Content:Dorit Gvili
Production:Dorit Gvili
Producer:Alon Shmoelof
Traffic Director:Ronit Doanis
Studio Director:Yaron Keinan
Studio:ATL
Postproduction:Leehou Porat
Editing:Leehou Porat

The Dot: a minimalist Braille smartwatch

Post pobrano z: The Dot: a minimalist Braille smartwatch

How do you read the time if you are visually impaired? There are probably solutions that involve audio with a smartwatch, but they will never be as elegant as this Braille watch.

The Dot is a smartwatch that comes with an app you can install on your phone, but it also includes mechanisms to give you the time using Braille. On top of telling you what time it is, the Dot can also send you notifications of phone calls and other things.

How to Create a Website That Gets a Lot of Traffic

Post pobrano z: How to Create a Website That Gets a Lot of Traffic

Businesses can never go wrong with setting up a website. For those selling products or offering a wide range of services, they will need to nurture an online presence as a means to generate potential customers.

It’s all easier said than done until you get to hit the ground running. For one, creating an effective web presence goes beyond establishing a website with your branding all over it. And it sure goes beyond asking people to visit your site in the hopes that you will be able to generate a sale.

Web traffic is the main goal for businesses that want to make the most out of their online efforts. It boils down to the way they craft their websites that would generate a lot of unique visits sourced from social media and organic searches.

Here are some tips you might want to consider:

1. Relevant content

More people will visit your site if you offer them something that’s valuable and relevant. With this in mind, the best way to capture your target customers is to generate informational and entertaining content.

For example, if you own a pet store and you want to attract reptile lovers, you will need to create content that resonates with the interests of this particular segment. You can write articles about the top tips for taking care of iguanas. You can also create colorful infographics that show the life cycle of a gecko and how to care for it at each stage of the cycle.

2. Optimize for SEO purposes

What’s a website without SEO? More importantly, what’s an online presence without SEO?

If anything, SEO gives your site the level of visibility it deserves in order to drive traffic from different sources. For this, you will need to make sure you have done effective keyword research and keyword planning before producing content for your site. Make sure you optimize your webpages by providing them with the right meta-data.

To further drive traffic to your site from other sources, you can also use a guest posting service. By getting a freelancer or an SEO firm to write about you on your behalf, you will be able to generate inbound links and build authority so that you are bound to get as many qualified visitors as you can.

3. Aim for consistent branding

What colors and fonts do you want to adopt for your brand?

Creating a brand kit is not just about drawing up a nifty logo. It also involves applying your brand’s identity to your website. This allows you to foster brand retention, which in turn compels existing customers to refer your site within their own networks.

4. Design with the intent to hold

It doesn’t help if your website is not designed properly. Slow loading speeds, confusing navigation, and crowded visual elements can turn off any online user, resulting in them exiting or bouncing off from your site, never to return again.

Don’t let this happen. In this sense, make sure to design your site with a clear focus on giving positive experiences to your online visitors. Doing so will give them a reason to advocate your business.

How to create a user friendly mobile app

Post pobrano z: How to create a user friendly mobile app

The usage of mobile technology and the number of users is constantly increasing. With the always-growing list of mobile activities, the focus is to upgrade individual features that combine into a modern mobile using experience.

The experience of a mobile user consists of the user’s approach and impressions prior to his mobile interaction; during his mobile interaction; and afterwards. It encompasses web browsing and applications on all types of mobile devices (low-featured smart phones to high definition tablets).

The ultimate result of technology improvement is that businesses have adjusted the quality of their mobile services to the same level of customer experience they offer in their stores.

Few ideas on how to build an excellent User-Friendly Mobile App Experience

Image source: Matteo Pasuto

The Customer sets the Rules

Due to the large choice and the severe competition, customers have more and more power to choose the appropriate device and to ensure that their mobile journey will be diverse and will include various channels.

They use several devices and as technology modernizes, they upgrade their smartphones, tablets or laptops. The key to keep them satisfied is to provide a persistent, excellent-quality interface and to guide their experience through few simple steps:

Recognizing Your Users’ Context

Image source: daRwin

Mobile experiences encompass large number of factors, some of them related to the app, while others with the personality of the user operating with it and the context of the operation.

For instance, checking your phone usually happens while you’re busy with a different activity. Most often, you’re trying to ‘kill time’ while traveling, having a coffee in the morning or waiting to reach the desk in a bank.

Clear Presentation

As we mentioned, people use their phones mostly when they are engaged in another, less divertive activity. Therefore, we must always approach their activities as something that is done rapidly, with no time to lose.

Image source: Fireart Studio

A user friendly app needs to use all of the real estate that can be found on the screen in a balanced manner. Your designs and layouts may appear perfect, but the secret lies in the fact they need to be equally applicable in every condition. For instance, it is very likely that your customer will have to use them with outside, rushing or facing a terrible connection, so you have to make sure they will remain applicable.

Remaining committed to Security

Your customer’s interactions and transactions need to be secured in every moment. It is the customers’ right and your obligation to employ secure user friendly mobile design and to cooperate only with vendors and other parties that share the same security commitment.

Marvelous Design

Image source: Zulal Ahmad

To start with, there is no general definition of good design. It simply depends on the taste and preferences of your customers. Design is a plan for arranging elements in such a way as best to accomplish a particular purpose.

If you’re looking for a more straightforward definition, good design is obvious. Great design is transparent. How to make a decision? Test it and check what your users think about it.

Gradual and Sustainable Improvement

Image source: Emre Durmus

The main rationale behind technological development is to empower people and to simplify their way of living. If you wish to remain on the scene, you have to follow every development and to remain innovative.

This is a ‘full-store’ chain-you have to develop your software, the partners you’re integrating, as well as the service you’re providing to your customers. It is only your creativity that can ensure optimal customer experience and bring you maximal results.

Avoiding design mistakes in the User-Friendly Mobile App Experience

It isn’t all about color

Image source: Dejan Markovic

A user-friendly app experience will be significantly bettered with interface decluttering. The best way to achieve this in your design is to employ a restricted palette of colors.

Learn from successful apps and try using the traditional black and white combination, but they apply sharper tones for headlines or other areas that need to be highlighted. They try to attract user’s attention with vivid red or orange. With no color diversity to distract them, users are free to navigate their interface without fearing to click on the wrong spot.

Icons are not random decoration tools

Image source: Hila Peleg

Their purpose is to ensure interaction, both in user friendly apps or websites. They save the designer some space, but offer enormous help to users who can perform their activities with a single click.

If created precisely, icons ensure an instinctive workflow without any need to rely on copy. On the other hand, messing things up would lead your customers out of the right path and it could ruin the image of your product.

Make sure the devices are compatible

The rule is one and only-in order to be user friendly, your app needs to be compatible with whatever device the user might be working on. That will inquire you to make constant compatibility tests with recent software releases.

There are numerous of excellent applications which failed just because the designer didn’t adjust them to popular software upgrades. Therefore, even if you consider your design to be perfect, you have to be aware there is a risk it will not run on an updated operative system.

Here are some tips that will keep your application usable: networking and constant communication with acknowledged designers in the branch, launching through a single “store”, and becoming unavoidably present on social media. All of this will help you to follow the trends and to adjust your design to them; to observe your own progress through customer feedback and to respond adequately.

Guidelines for creating people’s favorite user friendly app

Image source: Jakub Antalík

Get to know your users

What your users want is essential in user friendly mobile app design. You need to discover their motivation and to place triggers accordingly. Working on user experience will never be solid unless you are thinking the way your users do and unless you understand why they need the app you’re designing at the first place. Failing to do so will lead your conversion attempts to failure and will put an end to your growth tactic experiments.

Think seriously about the Offline experience

Many of the most popular apps base their usability on offline application. There should be no difference in the quality of their operation when connected to a signal or not. Designers should really take the importance of offline experience into account and think about how their application would look if applied without internet connection.

Employ Grids

Grids can help you to keep the consistency of your application when the users are switching from one page to the other. This famous design concept enables entrepreneurs to preserve their consistency, to establish excellent visual connections and to secure their design is unified throughout the entire app.

Cover all the Platforms that you can

It is no longer enough to think about all the devices your user could be in possession of. You should also consider the platforms he is using to access your application (Web browsers, Desktop) and to ensure that the app will be available, compatible and worth of their attention.

Replicate the Real World

The secret of designing a ‘blockbuster’ app is to provide fantastic experience resembling real life and responding to real needs. This task employs a serious dose of creativity, depending on the area, category or subject the app may represent.

Here is an example: If you are creating a productivity app, do some research on people’s behavior when using those particular products in real terms. That will enhance the user friendly mobile experience.

Essential to Remember

Image source: Cuberto

Designers do have the tendency to take mobile user experience for granted. They don’t employ too much creativity to delight their users and they seem to underestimate the complexity of mobile design.

It is a step-by-step procedure which consists of various mobile-characteristic considerations, tightly connected to smaller screens, varying device specifications, connection limitations, usage restrains, and the hardly identifiable modification-prone mobile context.

User friendly app design (both mobile or not) cannot be done in a rush. You need time to estimate precisely the behavior of your user, since he could always change paths statuses or interactions.

Skimping on foundation building is not an affordable luxury for a proper designer. He needs to understand the purpose: What is the aim of the app? Is it addressing a new need or improving an already existing one? Whatever you’re doing, focus on functionality. Your users will appreciate it!

 

How to use consistency in website design

Post pobrano z: How to use consistency in website design

Whenever designers take the time to sit down and design something new, there’s a lot more involved than just constructing a layout that looks appealing to viewers. It’s also important to establish a set of rules pertaining to exactly how an interface is able to handle various forms of information that it receives.

Later on down the road, if we decide to create something newer that essentially subverts the patterns and standards that we had previously established, we must have a rational explanation that is able to easily support this decision.

The main reason for this is because people will always learn to use all of our products thanks to all of the patterns and standards that we have established, regardless of whether or not good UX principles have been utilized.

Image source: truedigital.co.uk

Consistency in web design is something that will essentially help designers create systems that are effective. Design consistency is extremely important, even though the mere thought of it may sound completely uninteresting.

Structure and Interactions

Image source: lookback.io

Both of these are absolutely key to create a consistent page design and user interface. We often to forget about how both interaction and structure will affect user experience whenever we begin developing something. Creating a user interface that is usable and consistent is just as important as creating plans and blueprints for an entire home, for example.

Think about the following things before you begin making any attempts to write code: Consider how to place different elements consistently throughout your application and/or website. Contemplate what particular user interface patterns you will actually be using and think about what kind of input elements you will need the most.

You should also determine what icons you will actually need before selecting a good icon set that covers all of them

User interface patterns

Image source: Silk UI Kit

Start to think about what particular user interface patterns you will actually need to use the most, such as modals, accordions, and galleries. When you plan these things out ahead of time, not only will you be able to develop and design your application much more quickly, but you will also be able to figure out all of your content ahead of time as well. In the end, you stand to save a great deal of time, as you will have many of your pressing questions answered.

Consistency’s importance

Image source: inlayinsights.com

No one should ever have to wonder if the same things actually mean different things, or if different things actually mean the same things. Typically, if things look the same, then individuals will assume that they mean the same thing.

In the end, we are solely responsible for everything that we create. This means that it is entirely up to us to own that very responsibility and make sure that we do our best to put out nothing short of the best work possible, including making sure that everything is always consistent.

Designers are never truly able to change the outcomes of meetings, and any short-term decisions that are made can have effects that can end up being potentially problematic.

Making your designs consistent

Image source: rosewatermv.com

Consistency can’t be ensured by simple tasks such as creating style guides and defining user interface rules before emailing them around. Once those rules have actually been defined, it’s important to make sure that those rules are actually being observed properly.

The best way to do this is to define the user interface styles using various frameworks. These are able to assist the development teams stay consistent without actually having to do too much of the work themselves. Another useful tip is to engage in usability testing, gathering qualitative information, and addressing all issues that may arise.

Typography is also important, if you’re using serif fonts on a page, don’t switch to sans serif ones on a different page. It will confuse your users.

Elements

Image source: deploybot.com

Websites that use approximately three or four different kinds of border elements can come across as being really confusing at times. All of your borders should be kept on the following: Buttons, selects, inputs, galleries, images, other kinds of user interface elements.

Internal consistency

Image source: rudys.paris

External consistency can certainly enhance your overall user interface design due to meeting various kinds of user expectations. However, internal consistency is often viewed as more of a requirement that can actually cause harm to a user experience if it is not properly met.

When you deal with internal consistency, it’s important for you to try to cover all of the following: Color, Typography, Language, General visuals, Layout/location, Interactions.

Making a website consistent

Image source: Victor Erixon

If you want to make a website consistent, you should use the same colors throughout the entire thing. Also, there should be a consistent amount of horizontal and vertical spacing between all elements.

Navigation, which is very important, should be in the same location and text links always the same color. Make sure all the icons belong to the same family or have the same style.

Making sure your website is always consistent

One way to make sure that your website stays consistent is to use some kind of CSS framework, which will allow you to maintain a consistent layout at all times. If you have used a service such as WordPress to construct your website, you will easily be able to implement a service such as Bootstrap into your pages in order to help make this happen.

Ending thoughts

Image source: iqor.com

At times, you may feel that designing something merely for consistency is rather boring. You may feel, instead, that you want to include something as a surprise for your users, which is completely acceptable.

Nothing is wrong with keeping your users on their toes and wondering what may be coming next, so long as you don’t include so many things that will cause them to become so confused that they end up just wanting to go somewhere else.

Using data in React with the Fetch API and axios

Post pobrano z: Using data in React with the Fetch API and axios

If you are new to React, and perhaps have only played with building to-do and counter apps, you may not yet have run across a need to pull in data for your app. There will likely come a time when you’ll need to do this, as React apps are most well suited for situations where you’re handling both data and state.

The first set of data you may need to handle might be hard-coded into your React application, like we did for this demo from our Error Boundary tutorial:

See the Pen error boundary 0 by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

What if you want to handle data from an API? That’s the purpose of this tutorial. Specifically, we’ll make use of the Fetch API and axios as examples for how to request and use data.

The Fetch API

The Fetch API provides an interface for fetching resources. We’ll use it to fetch data from a third-party API and see how to use it when fetching data from an API built in-house.

Using Fetch with a third-party API

See the Pen React Fetch API Pen 1 by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

We will be fetching random users from JSONPlaceholder, a fake online REST API for testing. Let’s start by creating our component and declaring some default state.

class App extends React.Component {
  state = {
    isLoading: true,
    users: [],
    error: null
  }

  render() {
    <React.Fragment>
    </React.Fragment>
  }
}

There is bound to be a delay when data is being requested by the network. It could be a few seconds or maybe a few milliseconds. Either way, during this delay, it’s good practice to let users know that something is happening while the request is processing.

To do that we’ll make use of isLoading to either display the loading message or the requested data. The data will be displayed when isLoading is false, else a loading message will be shown on the screen. So the render() method will look like this:

render() {
  const { isLoading, users, error } = this.state;
  return (
    <React.Fragment>
      <h1>Random User</h1>
      // Display a message if we encounter an error
      {error ? <p>{error.message}</p> : null}
      // Here's our data check
      {!isLoading ? (
        users.map(user => {
          const { username, name, email } = user;
          return (
            <div key={username}>
              <p>Name: {name}</p>
              <p>Email Address: {email}</p>
              <hr />
            </div>
          );
        })
      // If there is a delay in data, let's let the user know it's loading
      ) : (
        <h3>Loading...</h3>
      )}
    </React.Fragment>
  );
}

The code is basically doing this:

  1. De-structures isLoading, users and error from the application state so we don’t have to keep typing this.state.
  2. Prints a message if the application encounters an error establishing a connection
  3. Checks to see if data is loading
  4. If loading is not happening, then we must have the data, so we display it
  5. If loading is happening, then we must still be working on it and display „Loading…” while the app is working

For Steps 3-5 to work, we need to make the request to fetch data from an API. This is where the JSONplaceholder API will come in handy for our example.

fetchUsers() {
  // Where we're fetching data from
  fetch(`https://jsonplaceholder.typicode.com/users`)
    // We get the API response and receive data in JSON format...
    .then(response => response.json())
    // ...then we update the users state
    .then(data =>
      this.setState({
        users: data,
        isLoading: false,
      })
    )
    // Catch any errors we hit and update the app
    .catch(error => this.setState({ error, isLoading: false }));
}

We create a method called fetchUser() and use it to do exactly what you might think: request user data from the API endpoint and fetch it for our app. Fetch is a promise-based API which returns a response object. So, we make use of the json() method to get the response object which is stored in data and used to update the state of users in our application. We also need to change the state of isLoading to false so that our application knows that loading has completed and all is clear to render the data.

The fact that Fetch is promise-based means we can also catch errors using the .catch() method. Any error encountered is used a value to update our error’s state. Handy!

The first time the application renders, the data won’t have been received — it can take seconds. We want to trigger the method to fetch the users when the application state can be accessed for an update and the application re-rendered. React’s componentDidMount() is the best place for this, so we’ll place the fetchUsers() method in it.

componentDidMount() {
  this.fetchUsers();
}

Using Fetch With Self-Owned API

So far, we’ve looked at how to put someone else’s data to use in an application. But what if we’re working with our own data in our own API? That’s what we’re going to cover right now.

See the Pen React Fetch API Pen 2 by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

I built an API which is available on GitHub. The JSON response you get has been placed on AWS — that’s what we will use for this tutorial.

As we did before, let’s create our component and set up some default state.

class App extends React.Component {
  state = {
    isLoading: true,
    posts: [],
    error: null
  }

  render() {
    <React.Fragment>
    </React.Fragment>
  }
}

Our method for looping through the data will be different from the one we used before but only because of the data’s structure, which is going to be different. You can see the difference between our data structure here and the one we obtained from JSONPlaceholder.

Here is how the render() method will look like for our API:

render() {
  const { isLoading, posts, error } = this.state;
  return (
    <React.Fragment>
      <h1>React Fetch - Blog</h1>
      <hr />
      {!isLoading ? Object.keys(posts).map(key => <Post key={key} body={posts[key]} />) : <h3>Loading...</h3>}
    </React.Fragment>
  );
}

Let’s break down the logic

{
  !isLoading ? 
  Object.keys(posts).map(key => <Post key={key} body={posts[key]} />) 
  : <h3>Loading...</h3>
}

When isLoading is not true, we return an array, map through it and pass the information to the Post component as props. Otherwise, we display a „Loading…” message while the application is at work. Very similar to before.

The method to fetch posts will look like the one used in the first part.

fetchPosts() {
  // The API where we're fetching data from
  fetch(`https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/posts.json`)
    // We get a response and receive the data in JSON format...
    .then(response => response.json())
    // ...then we update the state of our application
    .then(
      data =>
        this.setState({
          posts: data,
          isLoading: false,
        })
    )
    // If we catch errors instead of a response, let's update the app
    .catch(error => this.setState({ error, isLoading: false }));
}

Now we can call the fetchPosts method inside a componentDidMount() method

componentDidMount() {
  this.fetchPosts();
}

In the Post component, we map through the props we received and render the title and content for each post:

const Post = ({ body }) => {
  return (
    <div>
      {body.map(post => {
        const { _id, title, content } = post;
        return (
          <div key={_id}>
            <h2>Using data in React with the Fetch API and axios</h2>
            <p>{content}</p>
            <hr />
          </div>
        );
      })}
    </div>
  );
};

There we have it! Now we know how to use the Fetch API to request data from different sources and put it to use in an application. High fives. ✋

axios

OK, so we’ve spent a good amount of time looking at the Fetch API and now we’re going to turn our attention to axios.

Like the Fetch API, axios is a way we can make a request for data to use in our application. Where axios shines is how it allows you to send an asynchronous request to REST endpoints. This comes in handy when working with the REST API in a React project, say a headless WordPress CMS.

There’s ongoing debate about whether Fetch is better than axios and vice versa. We’re not going to dive into that here because, well, you can pick the right tool for the right job. If you’re curious about the points from each side, you can read here and here.

Using axios with a third-party API

See the Pen React Axios 1 Pen by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

Like we did with the Fetch API, let’s start by requesting data from an API. For this one, we’ll fetch random users from the Random User API.

First, we create the App component like we’ve done it each time before:

class App extends React.Component {
  state = {
    users: [],
    isLoading: true,
    errors: null
  };

  render() {
    return (
      <React.Fragment>
      </React.Fragment>
    );
  }
}

The idea is still the same: check to see if loading is in process and either render the data we get back or let the user know things are still loading.

To make the request to the API, we’ll need to create a function. We’ll call the function getUsers(). Inside it, we’ll make the request to the API using axios. Let’s see how that looks like before explaining further.

getUsers() {
  // We're using axios instead of Fetch
  axios
    // The API we're requesting data from
    .get("https://randomuser.me/api/?results=5")
    // Once we get a response, we'll map the API endpoints to our props
    .then(response =>
      response.data.results.map(user => ({
        name: `${user.name.first} ${user.name.last}`,
        username: `${user.login.username}`,
        email: `${user.email}`,
        image: `${user.picture.thumbnail}`
      }))
    )
    // Let's make sure to change the loading state to display the data
    .then(users => {
      this.setState({
        users,
        isLoading: false
      });
    })
    // We can still use the `.catch()` method since axios is promise-based
    .catch(error => this.setState({ error, isLoading: false }));
}

Quite different from the Fetch examples, right? The basic structure is actually pretty similar, but now we’re in the business of mapping data between endpoints.

The GET request is passed from the API URL as a parameter. The response we get from the API contains an object called data and that contains other objects. The information we want is available in data.results, which is an array of objects containing the data of individual users.

Here we go again with calling our method inside of the componentDidMount() method:

componentDidMount() {
  this.getUsers();
}

Alternatively, you can do this instead and basically combine these first two steps:

componentDidMount() {
  axios
    .get("https://randomuser.me/api/?results=5")
    .then(response =>
      response.data.results.map(user => ({
        name: `${user.name.first} ${user.name.last}`,
        username: `${user.login.username}`,
        email: `${user.email}`,
        image: `${user.picture.thumbnail}`
      }))
    )
    .then(users => {
      this.setState({
        users,
        isLoading: false
      });
    })
    .catch(error => this.setState({ error, isLoading: false }));
}

If you are coding locally from your machine, you can temporarily edit the getUsers() function to look like this:

getUsers() {
  axios
    .get("https://randomuser.me/api/?results=5")
    .then(response => console.log(response))
    .catch(error => this.setState({ error, isLoading: false }));
}

Your console should get something similar to this:

We map through the results array to obtain the information we need for each user. The array of users is then used to set a new value for our users state. With that done, we can then change the value of isLoading.

By default, isLoading is set to true. When the state of users is updated, we want to change the value of isLoading to false since this is the cue our app is looking for to make the switch from „Loading…” to rendered data.

render() {
  const { isLoading, users } = this.state;
  return (
    <React.Fragment>
      <h2>Random User</h2>
      <div>
        {!isLoading ? (
          users.map(user => {
            const { username, name, email, image } = user;
            return (
              <div key={username}>
                <p>{name}</p>
                <div>
                  <img src={image} alt={name} />
                </div>
                <p>{email}</p>
                <hr />
              </div>
            );
          })
        ) : (
          <p>Loading...</p>
        )}
      </div>
    </React.Fragment>
  );
}

If you log the users state to the console, you will see that it is an array of objects:

The empty array shows the value before the data was obtained. The returned data contains only the name, username, email address and image of individual users because those are the endpoints we mapped out. There is a lot more data available from the API, of course, but we’d have to add those to our getUsers method.

Using axios with your own API

See the Pen React Axios 2 Pen by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

You have seen how to use axios with a third-party API but we can look at what it’s like to request data from our own API, just like we did with the Fetch API. In fact, let’s use same JSON file we used for Fetch so we can see the difference between the two approaches.

Here is everything put together:

class App extends React.Component {
  // State will apply to the posts object which is set to loading by default
  state = {
    posts: [],
    isLoading: true,
    errors: null
  };
  // Now we're going to make a request for data using axios
  getPosts() {
    axios
      // This is where the data is hosted
      .get("https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/posts.json")
      // Once we get a response and store data, let's change the loading state
      .then(response => {
        this.setState({
          posts: response.data.posts,
          isLoading: false
        });
      })
      // If we catch any errors connecting, let's update accordingly
      .catch(error => this.setState({ error, isLoading: false }));
  }
  // Let's our app know we're ready to render the data
  componentDidMount() {
    this.getPosts();
  }
  // Putting that data to use
  render() {
    const { isLoading, posts } = this.state;
    return (
      <React.Fragment>
        <h2>Random Post</h2>
        <div>
          {!isLoading ? (
            posts.map(post => {
              const { _id, title, content } = post;
              return (
                <div key={_id}>
                  <h2>Using data in React with the Fetch API and axios</h2>
                  <p>{content}</p>
                  <hr />
                </div>
              );
            })
          ) : (
            <p>Loading...</p>
          )}
        </div>
      </React.Fragment>
    );
  }
}

The main difference between this method and using axios to fetch from a third-party is how the data is formatted. We’re getting straight-up JSON this way rather than mapping endpoints.

The posts data we get from the API is used to update the value of the component’s posts state. With this, we can map through the array of posts in render(). We then obtain the id, title and content of each post using ES6 de-structuring, which is then rendered to the user.

Like we did before, what is displayed depends on the value of isLoading. When we set a new state for posts using the data obtained from the API, we had to set a new state for isLoading, too. Then we can finally let the user know data is loading or render the data we’ve received.

async and await

Another thing the promise-based nate of axios allows us to do is take advantage of is async and await . Using this, the getPosts() function will look like this.

async getPosts() {
  const response = await axios.get("https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/posts.json");
  try {
    this.setState({
      posts: response.data.posts,
      isLoading: false
    });
  } catch (error) {
    this.setState({ error, isLoading: false });
  }
}

Base instance

With axios, it’s possible to create a base instance where we drop in the URL for our API like so:

const api = axios.create({
  baseURL: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/posts.json"
});

…then make use of it like this:

async getPosts() {
  const response = await api.get();
  try {
    this.setState({
      posts: response.data.posts,
      isLoading: false
    });
  } catch (error) {
    this.setState({ error, isLoading: false });
  }
}

Simply a nice way of abstracting the API URL.

Now, data all the things!

As you build React applications, you will run into lots of scenarios where you want to handle data from an API. Hopefully you know feel armed and ready to roll with data from a variety of sources with options for how to request it.

Want to play with more data? Sarah recently wrote up the steps for creating your own serverless API from a list of public APIs.

The post Using data in React with the Fetch API and axios appeared first on CSS-Tricks.

Agregator najlepszych postów o designie, webdesignie, cssie i Internecie