Categories
React Answers

How to make API call with hooks in React?

Sometimes, we want to make API call with hooks in React.

In this article, we’ll look at how to make API call with hooks in React.

How to make API call with hooks in React?

To make API call with hooks in React, we can do it in the useEffect callback.

For instance, we write

const Todo = () => {
  const [todo, setTodo] = React.useState(null);
  const [id, setId] = React.useState(1);

  const getTodo = async (id) => {
    const results = await fetch(
      `https://jsonplaceholder.typicode.com/todos/${id}`
    );
    const data = await results.json();
    setTodo(data);
  };

  React.useEffect(() => {
    if (id === null || id === "") {
      return;
    }
    getTodo(id);
  }, [id]);

  return (
    <div>
      <input value={id} onChange={(e) => setId(e.target.value)} />
      <br />
      <pre>{JSON.stringify(todo, null, 2)}</pre>
    </div>
  );
};

to define the getTodo which makes a get request to an endpoint to get some data.

We get the response data from the json method.

Then we call useEffect with a callback that calls getTodo with id.

The 2nd argument is [id] so the useEffect callback will be called when id changes.

Conclusion

To make API call with hooks in React, we can do it in the useEffect callback.

Categories
JavaScript Answers

How to add a grouped bar charts in chart.js and JavaScript?

Sometimes, we want to add a grouped bar charts in chart.js and JavaScript.

In this article, we’ll look at how to add a grouped bar charts in chart.js and JavaScript.

How to add a grouped bar charts in chart.js and JavaScript?

To add a grouped bar charts in chart.js and JavaScript, we add the data for each bar in the chart.

For instance, we write

const ctx = document.getElementById("myChart").getContext("2d");

const data = {
  labels: ["Chocolate", "Vanilla", "Strawberry"],
  datasets: [
    {
      label: "Blue",
      backgroundColor: "blue",
      data: [3, 7, 4],
    },
    {
      label: "Red",
      backgroundColor: "red",
      data: [4, 3, 5],
    },
    {
      label: "Green",
      backgroundColor: "green",
      data: [7, 2, 6],
    },
  ],
};

const myBarChart = new Chart(ctx, {
  type: "bar",
  data,
  options: {
    barValueSpacing: 20,
    scales: {
      yAxes: [
        {
          ticks: {
            min: 0,
          },
        },
      ],
    },
  },
});

to set data as the value of the data property in the object we call the Chart constructor with.

And we set the type to 'bar' so that the data will be rendered as a grouped bar chart.

Conclusion

To add a grouped bar charts in chart.js and JavaScript, we add the data for each bar in the chart.

Categories
JavaScript Answers

How to find all elements whose id begins with a common string with JavaScript?

Sometimes, we want to find all elements whose id begins with a common string with JavaScript.

In this article, we’ll look at how to find all elements whose id begins with a common string with JavaScript.

How to find all elements whose id begins with a common string with JavaScript?

To find all elements whose id begins with a common string with JavaScript, we call querySelectorAll.

For instance, we write

const dates = document.querySelectorAll('[id^="createdOnId"]');

to call querySelectorAll with '[id^="createdOnId"]' to return a node list with all elements that has ID starting with createdOnId.

Conclusion

To find all elements whose id begins with a common string with JavaScript, we call querySelectorAll.

Categories
JavaScript Answers

How to stop a requestAnimationFrame recursion or loop with JavaScript?

Sometimes, we want to stop a requestAnimationFrame recursion or loop with JavaScript.

In this article, we’ll look at how to stop a requestAnimationFrame recursion or loop with JavaScript.

How to stop a requestAnimationFrame recursion or loop with JavaScript?

To stop a requestAnimationFrame recursion or loop with JavaScript, we can add a flag to check when to stop calling requestAnimationFrame .

For instance, we write

let pause = false;
const loop = () => {
  //...
  if (pause) {
    return;
  }
  window.requestionAnimationFrame(loop);
};

loop();
pause = true;
loop();

to define the loop function that returns before calling requestionAnimationFrame if pause is true.

Then we call loop before and after we set pause to true.

Therefore, the first loop call will call requestionAnimationFrame and the 2nd one won’t.

Conclusion

To stop a requestAnimationFrame recursion or loop with JavaScript, we can add a flag to check when to stop calling requestAnimationFrame .

Categories
JavaScript Answers

How to get object property name with JavaScript?

Sometimes, we want to get object property name with JavaScript.

In this article, we’ll look at how to get object property name with JavaScript.

How to get object property name with JavaScript?

To get object property name with JavaScript, we use the Object.keys method.

For instance, we write

const result = Object.keys(myVar);
console.log(result[0]);

to call Object.keys with myVar to return an array of property key strings in the myVar object.

Then we get the first key from the array with result[0].

Conclusion

To get object property name with JavaScript, we use the Object.keys method.