Categories
React

How to make parallel queries 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 parallel queries with React Query?

Parallel Queries

Sometimes, we may want to make multiple GET requests concurrently.

To do this, we can add multiple useQuery hooks:

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 { data } = useQuery({
    queryKey: ["todo", 1],
    queryFn: ({ queryKey: [, id] }) => {
      return axios(`https://jsonplaceholder.typicode.com/posts/${id}`);
    }
  });
  const { data: yesNoData } = useQuery("yesNo", () =>
    axios("https://yesno.wtf/api")
  );

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

We have useQuery hooks to make 2 requests in parallel.

Dynamic Parallel Queries with useQueries Hook

We can add dynamic parallel queries with the useQueries hook.

It returns an array of query results.

For instance, we can write:

import axios from "axios";
import React from "react";
import { useQueries } from "react-query";
export default function App() {
  const todos = useQueries(
    Array(5)
      .fill()
      .map((_, i) => i + 1)
      .map((id) => {
        return {
          queryKey: ["todo", id],
          queryFn: ({ queryKey: [, id] }) => {
            return axios(`https://jsonplaceholder.typicode.com/posts/${id}`);
          }
        };
      })
  );

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

We call useQueries with an array of query objects.

We call map to map the array of numbers we created with:

Array(5)
  .fill()
  .map((_, i) => i + 1)

to query objects.

And todos is an array of query objects.

Dependent Queries

We can make also make multiple HTTP requests where one depends on the other.

To do this, we write:

import axios from "axios";
import React from "react";
import { useQuery } from "react-query";
export default function App() {
  const { data: id } = useQuery("id", () => Promise.resolve(1));

  const { data } = useQuery(
    ["todo", id],
    ({ queryKey: [, id] }) => {
      return axios(`https://jsonplaceholder.typicode.com/posts/${id}`);
    },
    {
      enabled: Boolean(id)
    }
  );

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

to make one query after the other.

We call the first useQuery hook to get an id for our todo.

Then we call useQuery again to pass in the id to the callback.

We set the enabled property to a boolean expression to indicate when we want to query to run.

We set it so that the 2nd query is run when id is truthy, which should only happen when we get the id from the first useQuery hook.

Conclusion

We can make parallel or sequential queries with React Query easily.

Categories
React

How to make queries 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 to make queries with React Query

How to make queries with React Query?

Query functions are functions that returns a promise and it’s passed into the 2nd argument of the useQuery hook.

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 { data } = useQuery("yesNo", () => axios("https://yesno.wtf/api"));

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

to return the promise return by the axios function.

The returned promises’ data will be set as the value of the data property.

Handling and Throwing Errors

React Query expects that an error is thrown in the query function when an error occurred.

If it doesn’t then we’ve to throw it ourselves.

For instance, we can write:

import React from "react";
import { useQuery } from "react-query";
export default function App() {
  const { error } = useQuery("todo", async () => {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/posts/100000000000"
    );
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    return response.json();
  });

  return <div>{error && error.message}</div>;
}

If we use the Fetch API to make HTTP requests, then we’ve to check whether the response.ok property is true .

If it’s not, then we’ve to throw an error to let React Query know that an error has occurred.

This has to be done since fetch doesn’t throw an error when we get a non-200 series response.

If response.ok is true , we return the response by calling response.json() .

Query Object

We can pass in a query object instead of pass in every as separate arguments to make our GET request.

For instance, we can write:

import axios from "axios";
import React from "react";
import { useQuery } from "react-query";
export default function App() {
  const { data } = useQuery({
    queryKey: ["todo", 1],
    queryFn: ({ queryKey: [, id] }) => {
      return axios(`https://jsonplaceholder.typicode.com/posts/${id}`);
    }
  });

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

queryKey has the identifier of the request.

queryFn is the function for making the request.

Conclusion

We can pass in functions that returns a promise to make requests to the useQuery hook to make GET requests with React.

Categories
JavaScript Answers

How to Set a DOM element as the First Child with JavaScript?

Sometimes, we may want to set a DOM element as the first child element with JavaScript.

In this article, we’ll look at ways to set a DOM element as the first child with JavaScript.

Using the prepend Method

In modern browsers, an HTML element object comes with the prepend method to let us prepend an element as the first child.

For instance, if we have the following HTML:

<div>  
  <p>  
    bar  
  </p>  
  <p>  
    baz  
  </p>  
</div>

Then we can write the following JavaScript to prepend an element as the first child of the div:

const div = document.querySelector('div')  
const newChild = document.createElement('p')  
newChild.textContent = 'foo'  
div.prepend(newChild)

We get the div with the document.querySelector method.

Then we call document.createElement to create an element.

Next, we set the textContent property to add some content to the p element we created.

And then we call div.prepend to prepend newChild as the first child of the div.

There’s also the append method to append an element as the last child of a parent element.

Using the insertAdjacentElement Method

We can also use the insertAdjacentElement method to insert an element as the first child of an element.

For instance, if we have the same HTML:

<div>  
  <p>  
    bar  
  </p>  
  <p>  
    baz  
  </p>  
</div>

Then we can write:

const div = document.querySelector('div')  
const newChild = document.createElement('p')  
newChild.textContent = 'foo'  
div.insertAdjacentElement('afterbegin', newChild)

to call insertAdjacentElement with 'afterbegin' and the newChild to prepend newChild as the first child element of the div.

Other possible values for the first argument of insertAdjacentElement is:

  • beforebegin: before the element itself.
  • beforeend: just inside the element, after its last child.
  • afterend: after the element itself.

Using the insertBefore Method

Another method we can use to prepend an element as the first child is to use the insertBefore method.

For instance, we can write:

const div = document.querySelector('div')  
const newChild = document.createElement('p')  
newChild.textContent = 'foo'  
if (div.firstChild) {  
  div.insertBefore(newChild, div.firstChild);  
} else {  
  div.appendChild(childNode);  
}

given the same HTML we have in the previous examples to prepend newChild as the first child of the div.

We check if there’s a firstChild element attached to the div.

If there is, then we call insertBefore to insert newChild before the firstChild of the div.

Otherwise, we just call appendChild to append newChild as a child element.

Conclusion

We can use various HTML element methods to prepend an element as the first child of a parent element.

Categories
JavaScript Answers

How to Declare Static Constants in JavaScript ES6 Classes?

Sometimes, we may want to declare static constants in our JavaScript classes.

In this article, we’ll look at how to declare static constants in ES6 JavaScript classes.

Add Getters in Our Class

To declare static constants in our ES6 classes, we can declare constants outside the class and add getters that return the constants in our class.

For instance, we can write:

const constant1 = 3,
  constant2 = 2;
class Example {
  static get constant1() {
    return constant1;
  }

  static get constant2() {
    return constant2;
  }
}

console.log(Example.constant1)
console.log(Example.constant2)

We declare constant1 and constant2 .

Then in the Example class, we create the constant1 and constant2 getters.

We add the static keyword before get so that we can make the static.

Then in the getter function, we return the constant1 and constant2 values respectively.

Likewise, we can write:

class Example {
  static get constant1() {
    return 3
  }

  static get constant2() {
    return 2
  }
}

Object.freeze(Example);
console.log(Example.constant1)
console.log(Example.constant2)

which is equivalent to what we have written above.

So when we log the values of Example.constant1 and Example.constant2 , we see 3 and 2 respectively.

Object.freeze

We can freeze the class to make the whole class immutable.

To do this, we write:

class Example {}
Example.constant1 = 3
Example.constant2 = 2
Object.freeze(Example);
console.log(Example.constant1)
console.log(Example.constant2)

We add our static properties with:

Example.constant1 = 3
Example.constant2 = 2

This works since classes are constructor functions, which are objects.

This also means we can use the Object.freeze method on Example to make the Example class immutable.

So we can log the values of the Example.constant1 and Example.constant2 properties and get their values.

We should see 3 and 2 respectively.

Conclusion

We can declare static constants in our JavaScript class by declaring static getters that returns constants declared outside the class.

Also, we can freeze the class with the Object.freeze method since it’s a regular object.

This makes the class immutable.

Categories
JavaScript Answers

How to Resize HTML5 Canvas to Fit the Window with JavaScript?

Sometimes, we may want to resize an HTML5 canvas to fit the window that it’s in with JavaScript.

In this article, we’ll look at how to resize an HTML5 canvas to fit the window with JavaScript.

Setting the width and height Properties of the Canvas

We can just set the width and height properties of the canvas as the window resizes to set the width and height of the canvas to change its size.

For instance, we can write:

const draw = (canvas) => {
  const ctx = canvas.getContext("2d");
  ctx.beginPath();
  ctx.arc(95, 50, 40, 0, 2 * Math.PI);
  ctx.stroke();
}

const canvas = document.querySelector("canvas");
canvas.width = window.innerWidth
canvas.height = window.innerHeight
draw(canvas)

window.addEventListener('resize', () => {
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight
  draw(canvas)
})

to change the size of the canvas initialize to the window’s dimensions with:

canvas.width = window.innerWidth
canvas.height = window.innerHeight

And we do the same thing in the resize event listener, which we added with the addEventListener method.

When the canvas resizes the content disappears, so they have to be drawn again whenever we resize the canvas by setting the width and height properties.

Set the Size with CSS

We can also set the size of the canvas with CSS to make it fill the screen.

For instance, we can write the following HTML:

<canvas></canvas>

And the following CSS:

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
}

canvas {
  background-color: #ccc;
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

to set the canvas’s width and height both to 100%.

We also set the position to absolute and top , left , right , and bottom to 0 to make the canvas fill the screen.

Also, we make the html and body elements fill the screen by setting the width and height to 100%.

And we can draw on it with:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();

We draw a circle with the arc method.

We have the center x and y coordinates, radius, and start and end angles in radians as arguments in this order.

Conclusion

We can resize the canvas to fit the screen with JavaScript or CSS.