Categories
React

Making HTTP Requests with React Query — GET Requests

The React Query library lets us make HTTP requests easily in our React apps.

In this article, we’ll look at how to make HTTP requests with React Query.

GET Requests with the useQuery Hook

To make GET requests, we use the useQuery hook provided by React Query.

For instance, we can write:

index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { QueryClient, QueryClientProvider } from "react-query";
import App from "./App";

const queryClient = new QueryClient();

const rootElement = document.getElementById("root");
ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <StrictMode>
      <App />
    </StrictMode>
  </QueryClientProvider>,
  rootElement
);

App.js

import axios from "axios";
import React from "react";
import { useQuery } from "react-query";

export default function App() {
  const { isLoading, isError, data, error } = useQuery("yesNo", () =>
    axios("https://yesno.wtf/api")
  );

  if (isLoading) {
    return <span>Loading...</span>;
  }

  if (isError) {
    return <span>Error: {error.message}</span>;
  }

  return <div>{JSON.stringify(data)}</div>;
}

We wrap our App with the QueryClientProvider higher-order component to let us use the hooks provided by React Query to make HTTP requests.

Then in App , we call useQuery with an identifier for the request as the first argument.

The 2nd argument has the function that makes the HTTP request.

It should return a promise with the response data.

The hook returns an object with various properties.

isLoading is true when the request is loading.

isError is true when the request has an error.

data has the response data.

error has the error content.

We can replace the boolean properties with the status property.

For instance, we can write:

import axios from "axios";
import React from "react";
import { useQuery } from "react-query";

export default function App() {
  const { status, data, error } = useQuery("yesNo", () =>
    axios("https://yesno.wtf/api")
  );

  if (status === "loading") {
    return <span>Loading...</span>;
  }

  if (status === "error") {
    return <span>Error: {error.message}</span>;
  }

  return <div>{JSON.stringify(data)}</div>;
}

If status is 'loading' , then the request is loading.

If status is 'error' , then the request has an error.

Query Keys

Query keys are the first argument of the useQuery .

It identifies the request being made uniquely.

We can pass in a string as we did in the above examples.

But we can also pass in array keys if we need to pass in more information to identify the request.

For instance, we can write:

import axios from "axios";
import React from "react";
import { useQuery } from "react-query";

export default function App() {
  const { status, data, error } = useQuery(
    ["todo", 5],
    ({ queryKey: [, id] }) => {
      return axios(`https://jsonplaceholder.typicode.com/posts/${id}`);
    }
  );

  if (status === "loading") {
    return <span>Loading...</span>;
  }

  if (status === "error") {
    return <span>Error: {error.message}</span>;
  }

  return <div>{JSON.stringify(data)}</div>;
}

to call useQuery with an array key.

We can get the key’s content with the queryKey property of the parameter in the callback in the 2nd argument.

We get the id from the 2nd entry of the array just like how we passed them in.

Conclusion

We can make GET requests easily in our React app with React Query.

Categories
React

Getting Started with Making HTTP Requests with React Query

The React Query library lets us make HTTP requests easily in our React apps.

In this article, we’ll look at how to make HTTP requests with React Query.

Installation

We can install the library by running:

npm i react-query

or:

yarn add react-query

We also install the Axios HTTP client library to let us make requests easier.

To do this, we run:

npm i axios

Getting Started

We can then make a query with the API by writing:

index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { QueryClient, QueryClientProvider } from "react-query";
import App from "./App";

const queryClient = new QueryClient();

const rootElement = document.getElementById("root");
ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <StrictMode>
      <App />
    </StrictMode>
  </QueryClientProvider>,
  rootElement
);

App.js

import axios from "axios";
import React from "react";
import { useQuery } from "react-query";

export default function App() {
  const { isLoading, error, data } = useQuery("yesNo", () =>
    axios("https://yesno.wtf/api")
  );

  if (isLoading) return "Loading...";

  if (error) return "An error has occurred: " + error.message;

  return <div>{JSON.stringify(data)}</div>;
}

We wrap our App component around the QueryClientProvider component to let us use its hooks to make requests.

Then in App , we use the useQuery hook to make a GET request.

The first argument is a string identifier for our query.

The 2nd argument has a function to let us make the request.

The isLoading state indicates the request is loading when it’s truthy.

error state indicates that an error occurred when it’s truthy.

data has the response data.

Making POST Requests

To make POST requests, we can use the useMutation hook.

To do this, we write:

import axios from "axios";
import React from "react";
import { useMutation, useQueryClient } from "react-query";

export default function App() {
  const queryClient = useQueryClient();
  const mutation = useMutation(
    (data) => axios.post("https://jsonplaceholder.typicode.com/posts", data),
    {
      onSuccess: () => {
        queryClient.invalidateQueries("todos");
      }
    }
  );

  return (
    <div>
      <button
        onClick={() => {
          mutation.mutate({
            title: "foo",
            body: "bar",
            userId: 1
          });
        }}
      >
        Add Todo
      </button>
    </div>
  );
}

We keep index.js the same as in the previous example.

We call the useQueryClient hook to get the query client.

useMutation lets us make the request by passing in a callback that returns a promise by calling axios.post with the URL and request body we want.

The 2nd argument has an object that has the onSuccess callback that runs when the request succeeds.

We call queryClient.invalidaQueries with the identifier of the requests to clear resources.

Conclusion

We can make HTTP requests easily with the React Query library.

Categories
JavaScript Answers

How to Display JavaScript DateTime in 12 Hour AM/PM Format?

Sometimes, we may want to display a JavaScript date-time in 1 hour AM/PM format.

In this article, we’ll look at how to format a JavaScript date-time into 12 hour AM/PM format.

Create Our Own Function

One way to format a JavaScript date-time into 12 hour AM/PM format is to create our own function.

For instance, we can write:

const formatAMPM = (date) => {
  let hours = date.getHours();
  let minutes = date.getMinutes();
  let ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12;
  minutes = minutes.toString().padStart(2, '0');
  let strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime;
}

console.log(formatAMPM(new Date(2021, 1, 1)));

We have the formatAMPM function that takes a JavaScript date object as a parameter.

In the function, we call getHours tio get the hours in 24 hour format.

minutes get the minutes.

Then we create the ampm variable and it to 'am' or 'pm' according to the value of hours .

And then we change the hours to 12 hour format by using the % operator to get the remainder when divided by 12.

Next, we convert minutes to a string with toString and call padStart to pad a string with 0 if it’s one digit.

Finally, we put it all together with strTime .

So when we log the date, we get:

12:00 am

Date.prototype.toLocaleString

To make formatting a date-time to AM/PM format easier, we can use the toLocaleString method.

For instance, we can write:

const str = new Date(2021, 1, 1).toLocaleString('en-US', {
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
})
console.log(str);

We call toLocaleString on our date object with the locale and an object with some options.

The hour property is set to 'numeric' to display the hours in numeric format.

This is the same with minute .

hour12 displays the hours in 12-hour format.

So str is ‘1’2:00 AM’ as a result.

Date.prototype.toLocaleTimeString

We can replace toLocaleString with toLocaleTimeString and get the same result.

For instance, we can write:

const str = new Date(2021, 1, 1).toLocaleTimeString('en-US', {
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
})
console.log(str);

And we get the same result.

moment.js

We can also use moment.js to format a date object into a 12-hour date-time format.

To do this, we call the format method.

For example, we can write:

const str = moment(new Date(2021, 1, 1)).format('hh:mm a')
console.log(str);

And we get the same result as before.

a adds the AM/PM.

hh is the formatting code for a 2 digit hour.

mm is the formatting code for a 2 digit minute.

Conclusion

We can format a JavaScript date-time to 12-hour format with vanilla JavaScript or moment.js.

Categories
JavaScript Answers

How to Create a style Tag with JavaScript?

Sometimes, we may want to create a style tag dynamically within our web page.

In this article, we’ll look at how to create a style tag dynamically with JavaScript.

Create a style Element with createElement Attach it to the head Tag with appendChild

We can create a style element with the docuemnt.createElement method as we do with any other kind of element.

Then we can attach the created element to the head tag by writing:

const style = document.createElement('style')
style.type = 'text/css';
style.textContent = 'h1 { color: green }';
document.head.appendChild(style)

We create the style element with document.createElement .

Then we set the type property of it to 'text/css' .

And then we set the textContent of the style element to the styles we want.

Finally, we call document.head.appendChild to append the style element to the head tag as a child.

We can now add the following HTML:

<h1>
  hello
</h1>

And we that the h1 text is green.

document.head.insertAdjacentHTML Method

We can also use the document.head.insertAdjacentHTML method to add our own HTML into the head tag.

This includes inserting a style element into the head tag.

To do this, we write:

document.head.insertAdjacentHTML("beforeend", `
  <style>
    h1 { color :green }
  </style>
`)

We pass in beforeend to insert the style element before the closinghead tag.

And so we get the same result as before.

Inserting a Stylesheet Dynamically

We can also insert a CSS stylesheet dynamically.

For instance, we can write:

const ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css";
document.head.appendChild(ss);

We create the link element with the document.createElement method.

Then we set the type to 'text/css' to make it reference a CSS stylesheet.

rel sets the rel attribute to stylesheet .

href sets the href attribute to the CSS file we want to reference.

Then we call document.head.appendChild to append the CSS.

And now we get the styles from the Bootstrap stylesheet applied in our app.

Conclusion

We can create a style element with JavaScript or add a link tag dynamically to reference to external CSS with JavaScript to add styles dynamically.

Categories
JavaScript Answers

How to Insert a JavaScript Substring at a Specific Index of an Existing String?

Sometimes, we may want to insert a JavaScript substring at a specific index of an existing string.

In this article, we’ll look at how to insert a JavaScript substring at a specific index of an existing string.

String.prototype.slice

We can call slice on a string with the start and end indexes to extract a substring from the start index to the end index minus 1.

So we can use it to break the existing string into 2 substrings with the index that we want to insert the substring to.

And we can put the substring in between the 2 broken substrings.

For instance, we can write:

const txt1 = 'foobaz'  
const txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);  
console.log(txt2)

We have txt1 set to 'foobar' .

And we want to insert 'baz' between 'foo' and 'baz' .

To do this, we call slice with start index 0 and end index 3 to extract the segment between index 0 and 2.

And we call slice again to extract the substring from index 3 to the end of the string.

Then we concatenate the strings together with + .

So we get 'foobarbaz’ as a result.

String.prototype.substring

We can replace the slice method with the substring method.

It takes the same arguments as slice .

So we can write:

const txt1 = 'foobaz'  
const txt2 = txt1.substring(0, 3) + "bar" + txt1.substring(3);  
console.log(txt2)

And we get the same value for txt2 .

Conclusion

We can insert a substring into an existing at the existing index with the JavaScript string’s slice or substring methods.