Experiencing difficulty in connecting with the service providers

What's the process for obtaining these providers?

I recently followed the JavaScript Mastery tutorial step by step, however, I encountered an issue with the useEffect hook to fetch the providers (I even tried using alert to check, but it keeps showing null).

Below is the code snippet that includes the providers - please help me identify what could be wrong:

const [providers, setProviders] = useState(null);
 const [toggleDropdown, setToggleDropdown] = useState(false);

 useEffect(() => {
   const setUpProviders = async () => {
     const response = await getProviders();
     setProviders(response);
   };

   setUpProviders();
 }, []);

Answer №1

This is the normal behavior of the useState hook. To monitor when your variable updates, you can utilize the useEffect.

const [providers, setProviders] = useState(null);
const [toggleDropdown, setToggleDropdown] = useState(false);

useEffect(() => {
  const setUpProviders = async () => {
    const response = await getProviders();
    setProviders(response);
  };

  setUpProviders();
}, []);

useEffect(() => {
  console.log(providers)
}, [providers])

To delve deeper into this behavior, visit this link

Answer №2

check out the complete code :

    "use client";

import Link from "next/link";
import Image from "next/image";
import { useState, useEffect } from "react";
import 
{ signIn, signOut, useSession, getProviders }
from "next-auth/react";

const Navigation = () => {
  const { data: session } = useSession();
  const [providers, setProviders] = useState(null);
  const [toggleDropdown, setToggleDropdown] = useState(false);

  useEffect(() => {
    (async () => {
      const res = await getProviders();
      setProviders(res);
    })();
  }, []);

  useEffect(() => {
    alert(providers);
  }, [providers]);

  return (
    <nav className="flex-between w-full mb-16 pt-3">
      <Link href="/" className="flex gap-2 flex-center">
        <Image
          src="/assets/images/logo.svg"
          alt="Promptopia logo"
          width={30}
          height={30}
          className="object-contain"
        />
        <p className="logo_text">Promptopia</p>
      </Link>
      <div className="sm:flex hidden">
        {session?.user ? (
          <div className="flex gap-3 md:gap-5">
            <Link href="/create-prompt" className="black_btn">
              Create Post
            </Link>

            <button type="button" onClick={signOut} className="outline_btn">
              Sign Out
            </button>

            <Link href="/profile">
              <Image
                src="/assets/images/logo.svg"
                width={37}
                height={37}
                className="rounded-full"
                alt="profile"
              />
            </Link>
          </div>
        ) : (
          <>
            {providers && Object.values(providers).map((provider) => (
              <button
                type="button"
                key={provider.name}
                onClick={() => signIn(provider.id)}
                className="black_btn"
              >
                Sign In
              </button>
            ))}
          </>
        )}
      </div>
      <div className="sm:hidden flex relative">
        {session?.user ? (
          <div className="flex">
            <Image
              src="/assets/images/logo.svg"
              width={37}
              height={37}
              className="rounded-full"
              alt="profile"
              onClick={() => setToggleDropdown((prev) => !prev)}
            />

            {toggleDropdown && (
              <div className="dropdown">
                <Link
                  href="/profile"
                  className="dropdown_link"
                  onClick={() => setToggleDropdown(false)}
                >
                  My Profile
                </Link>
                <Link
                  href="/create-prompt"
                  className="dropdown_link"
                  onClick={() => setToggleDropdown(false)}
                >
                  Create Prompt
                </Link>
                <button
                  type="button"
                  onClick={() => {
                    setToggleDropdown(false);
                    signOut();
                  }}
                  className="mt-5 w-full black_btn"
                >
                  Sign Out
                </button>
              </div>
            )}
          </div>
        ) : (
          <>
            {providers && Object.values(providers).map((provider) => (
              <button
                type="button"
                key={provider.name}
                onClick={() => signIn(provider.id)}
                className="black_btn"
              >
                Sign In
              </button>
            ))}
          </>
        )}
      </div>
    </nav>
  );
};

export default Navigation;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the optimal arrangement for constructors or classes in JavaScript code?

Constructors, being objects that are stored as copies, appear to behave similarly to variables in terms of their placement within the code. Unlike functions, constructors cannot be placed "anywhere" and must instead be positioned above the area where they ...

Error: Unexpected token : encountered in jQuery ajax call

When creating a web page that requests remote data (json), using jQuery.ajax works well within the same domain. However, if the request is made from a different domain (e.g. localhost), browsers block it and display: No 'Access-Control-Allow-Or ...

Expand the boundaries of the MUI Select to encompass a different element

Is there a way to extend the border of the MUI Select dropdown menu around the IconButton next to it? I have set up sorting options (A-Z, newest-oldest) using the Select component and included a button to reverse the direction (Z-A, oldest-newest). However ...

Ways to exchange information among Vue components?

My role does not involve JavaScript development; instead, I focus on connecting the APIs I've created to front-end code written in Vue.js by a third party. Currently, I am struggling to determine the hierarchy between parent and child elements when ac ...

Removing unnecessary keys from intricate JSON data (with the use of pure JavaScript)

I've experimented with various methods to dynamically parse and remove keys with empty values from a JSON file using JavaScript. Currently, I can successfully delete non-nested keys, except for empty strings that have a length greater than 0. My mai ...

What is the best approach for assigning a value to the action URL in el-upload?

<el-upload class="upload" action="http://127.0.0.1:5000/upload/email" :file-list="fileList" > Utilizing the Element UI library, I am attempting to pass an email value to the 'action' URL in the format of base_ ...

How can I ensure security measures are in place to avoid XSS attacks on user-generated HTML content?

Currently, I am in the process of developing a web application that will allow users to upload entire web pages onto my platform. My initial thought was to utilize HTML Purifier from http://htmlpurifier.org/, but I am hesitant because this tool alters the ...

Transitioning from the older version of Angular (1.0.8) to the newer version (1.2.0

Transitioning to the latest production version of Angular has been quite challenging for me. I have meticulously followed the migration guidelines, focusing mainly on the underscore prefix \ private attributes section that seemed relevant to my situa ...

How can one effectively overcome the constraint in HTML5 canvas that prevents altering the positions of previously sketched elements?

I am currently working on creating a wind map that displays data from seven different weather stations. My goal is to develop a fluid and interactive map similar to the ones found in this animation or this animation. In my research, I came across an artic ...

Tips on altering the input's background color using nextui?

I am currently facing an issue while working with NextJs, TailwindCss, and NextUI. When trying to use the inputs, I found the default white color unappealing. Despite numerous attempts to change the color in various ways, I still end up with this undesired ...

Having difficulty adding a custom library from a repository into an Ember project as a dependency

I've been working on a WebGL library that I want to include as a dependency in an EmberJS project. It seems like I should be able to do this directly from the repository without creating an npm package, but I'm running into some issues. To illus ...

Is localStorage.getItem() method in NextJS components behaving differently?

I'm working on my nextjs application and I wanted to utilize the power of localstorage for storing important data throughout my app. Within the pages directory, specifically in the [slug].tsx file, I implemented the following logic: export default fu ...

Tips for refreshing information in the Angular front-end Grid system?

I am currently working with the Angular UI Grid. The HTML code snippet in my file looks like this. <div ui-grid="gridOptions"></div> In my controller, I have the following JavaScript code. $scope.values = [{ id: 0, name: 'Erik&a ...

Transitioning the style code from inline to the head of the document disrupts the straightforward JavaScript intended to

As I delve into the world of web development, I encountered a simple issue that has been causing me frustration for the past hour. It involves code to display the border color of a div element using an alert. The code works perfectly fine when the style is ...

How to create a CSS animation that gradually darkens a background image during a

Currently in the process of constructing a page with an intriguing background image: body { background:url(images/bg.png) center center no-repeat fixed; -webkit-background-size:cover; -moz-background-size:cover; -o-background-size:cover; ...

Tips for designing a multi-level dropdown navbar

I am currently facing an issue with designing a navbar. I am aiming for Multi-Level Dropdowns, but whenever I click on More Services, it automatically closes the main dropdown menu. I have experimented with various approaches, but none of them seem to be ...

Using Facebook authentication in React Native

Currently developing a React Native app and aiming to incorporate Facebook login functionality. The back-end logic for user authentication is handled by an API in Node.js. Utilizing passport.js to enable users to log in using either Facebook or Email cre ...

Create a single JSON object by searching through two collections in MongoDB

Is it possible for you to assist me in combining data from two collections into one JSON format? Users [ user_id, user_name, city_id ] [ { "name": "Anton", "user_id": 1, "city_id": 1 }, { "name": "Vasiliy", ...

VueJS together with Firebase: The guide to password validation

I am currently working on a web form developed using VueJS that enables authenticated users to modify their passwords. The backend system relies on Firebase, and I am facing a challenge in validating the user's current password before initiating the p ...

Styling extracted content using headless browsing algorithm

Is there a way to format the scraped text from multiple elements on the page for use elsewhere? I have JavaScript code that can loop over the elements, add their text to an array, and turn it into a string, achieving the desired formatting. How can I inc ...