afewminutesofcode.com

Create a weather voice assistant in React

Cover Image for Create a weather voice assistant in React

In this tutorial we are going to create a simple React app that will use the speechSynthesis API to speak the current temperature in the city we type in.

Prerequisites

Firstly we will create the UI for the page. (For simplicity only basic styling will be done here.)

      <div className="wrapper">
        <div>
          <p>Type in a city to see the current weather.</p>
          <input id="city" type="text" />
          <button
            onClick={() => speakTheWeather(document.getElementById("city").value)}
          >
            search
          </button>
        </div>
      </div>
))}

Now we will create a function called speakTheWeather that will use SpeechSynthesisUtterance to tell us the weather.

const speakTheWeather = (city) => {
  let msg = new SpeechSynthesisUtterance();
  const voices = window.speechSynthesis.getVoices();
  msg.voice = voices[0];
  msg.text = "Tell me the weather";
  speechSynthesis.speak(msg);
};

So far when we type a city and click search our assistant will say Tell me the weather. There is a lot of configuration you can do with the voice including pitch,lang,rate,voice,volume and the results from these configurations can vary from browser/device. See the MDN Website for more details.

Now we will extend our function to tell us the weather so we will fetch the weather from the specified city as shown below. Note we will store our API details in another file, the value of the WEATHER_API is https://community-open-weather-map.p.rapidapi.com/weather?units=metric.

In the below code if we type in a city that the api has a result for we will hear our browser say eg The current TEMPERATURE for London is 25 degrees. If we input a value it can't find it will say unable to get the TEMPERATURE for ...

const speakTheWeather = (city) => {
  let msg = new SpeechSynthesisUtterance();
  const voices = window.speechSynthesis.getVoices();
  msg.voice = voices[0];
  fetch(`${WEATHER_API}&q=${city}`, {
    headers: {
      "X-RapidAPI-Key": WEATHER_API_KEY,
    },
  })
    .then(function (response) {
      return response.json();
    })
    .then(function (myJson) {
      msg.text = `The current TEMPERATURE for ${city} is ${myJson.main.temp} degrees`;
      speechSynthesis.speak(msg);
    })
    .catch(function (err) {
      msg.text = `unable to get the TEMPERATURE for ${city}`;
      speechSynthesis.speak(msg);
    });
};

And there we have it our browser now speaks tells us the Temperature for the city we type in. We will add one more change to the code and add in a sessionStorage layer to the code so that we only call the api once for each city in each session.

const speakTheWeather = (city) => {
  let msg = new SpeechSynthesisUtterance();
  const voices = window.speechSynthesis.getVoices();
  msg.voice = voices[0];
  if (sessionStorage[city] !== undefined) {
    msg.text = `The current TEMPERATURE for ${city} is ${sessionStorage[city]} degrees`;
    speechSynthesis.speak(msg);
  } else {
    fetch(`${WEATHER_API}&q=${city}`, {
      headers: {
        "X-RapidAPI-Key": WEATHER_API_KEY,
      },
    })
      .then(function (response) {
        return response.json();
      })
      .then(function (myJson) {
        sessionStorage[city] = myJson.main.temp;
        msg.text = `The current TEMPERATURE for ${city} is ${myJson.main.temp} degrees`;
        speechSynthesis.speak(msg);
      })
      .catch(function (err) {
        msg.text = `unable to get the TEMPERATURE for ${city}`;
        speechSynthesis.speak(msg);
      });
  }
};

Now you have the power to use the speechSynthesis api how are you going to incorporate it into your app?

See working example on codesandbox

You might also like

Cover Image for Check if a string contains a substring in JavaScript

Check if a string contains a substring in JavaScript

Since ES6 you can now use the built in includes method eg string.includes(substring).

Cover Image for Create a Cricket Points Table in Javascript - Part 5

Create a Cricket Points Table in Javascript - Part 5

In this tutorial we are going to build our points table based off our previous work.

Cover Image for Create a Cricket Points Table in Javascript - Part 4

Create a Cricket Points Table in Javascript - Part 4

In this tutorial we are going to complete the rest of the calculations required for the points table.

Cover Image for Create a Cricket Points Table in Javascript - Part 3

Create a Cricket Points Table in Javascript - Part 3

In this tutorial we are going to create functions to calculate the total number of wins, losses, no results and points a team has for the tournament.

Cover Image for Create a Cricket Points Table in Javascript - Part 2

Create a Cricket Points Table in Javascript - Part 2

In this tutorial we are going to create a function to calculate when a team has won, lost or there is no result.

Cover Image for Create a Cricket Points Table in Javascript - Part 1

Create a Cricket Points Table in Javascript - Part 1

In this tutorial we are going to Create a Cricket Points Table in JavaScript.

Cover Image for Create a weather voice assistant in React

Create a weather voice assistant in React

In this tutorial we are going to create a simple React app that will use the speechSynthesis API to speak the current temperature in the city we type in.

Cover Image for Getting to know the many voices in your browser

Getting to know the many voices in your browser

The Speech Synthesis API has been around since about 2014 but still has not gained a huge amount of traction on many sites.

Cover Image for How to create a custom sort order in javascript

How to create a custom sort order in javascript

When sorting an array of objects in JavaScript, usually we will want to sort alphabetically or numerically, but there are also some cases were we might need a custom sort order.

Cover Image for How to sort an array alphabetically in javascript

How to sort an array alphabetically in javascript

To sort an array alphabetically in javascript you can use the sort function.

Cover Image for How to sort an array numerically in javascript

How to sort an array numerically in javascript

To sort an array in javascript use the sort method sort((a, b) => a - b)

Cover Image for How to convert an array into an object in javascript

How to convert an array into an object in javascript

To convert an array into an object we will create a function and give it 2 properties, an array and a key..

Cover Image for How to filter an array in javascript

How to filter an array in javascript

To filter an array in Javascript we can pass in a condition to the built in filter function.