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

Positioning an element in the center of another using JQuery

Greetings! I am currently working with some elements that look like this: <div id="one">content</div> <div id="two">content</div> These elements are followed by another set of elements (without any parent, placed directly after th ...

Measuring the success of Vuejs app

Seeking performance metrics for a Vue application. Interested in metrics for the entire app as well as specific components. I am aware of using Vue.config.performance = true; to enable performance monitoring through dev tools, and I have considered utiliz ...

Verify whether the keys of Object1 exist in Object2; if they do, compare their corresponding values

How can I accomplish the following task? I want to check if the keys of object1 are present in object2. If a key is found, I need to compare its value with that of object2. If the values are different, I should replace the value in object2 with the one fro ...

Can "Operator" be used as a function parameter?

Take a look at this code snippet: const myFunction = (x, y, z) => { //Some code here }; $('whatever').on( event, function(){ myFunction( event.originalEvent && event.originalEvent.target ); //What is this operator doing? }); Can yo ...

``The error 'Uncaught SyntaxError' is thrown during the production build of

I am facing an issue with the production build of my Vuejs application. When I use the npm run build command to generate the production build and then use serve -s dist to deploy it, everything works fine except for one parameterized path (product) in Vue ...

Mongoose Error: The function 'mongooseSchemahere' is not recognized as a valid function

Here is the mongoose Schema setup in models/user.js: const mongoose = require('mongoose'); const userSchema = mongoose.Schema({ loginId: String, firstname: String, lastname: String, eMail: String, password: String, acti ...

Experimenting with the speechSynthesis API within an iOS webview application

I'm currently working on developing an app that features TTS capabilities. Within my webview app (utilizing a React frontend compiled with Cordova, but considering transitioning to React Native), I am implementing the speechSynthesis API. It function ...

Error in NextJS export: location is not defined

In my NextJS app, I declare Pages to be client-side by using the "use client" directive at the beginning of the file. However, when I attempt to build the application, I encounter errors: Error occurred prerendering page "/". Read more: ...

Concentrating on a Div Element in React

I'm trying to set up an onKeyPress event that will be triggered when a key is pressed while a 'Level' element is displayed. I know that the div needs to be focused for events to register, but I'm not sure how to do this with functional ...

How to retrieve the chosen option from a drop-down menu created within a loop in a React application

I am seeking guidance on the best way to create multiple drop-down menus (<select>) using a loop, so that I can retrieve their selected values using a button. I have attempted to replicate what is currently in my code, hoping this information is suff ...

Revamp MUI class names with React Material UI's innovative randomization and elimination

Can names be randomized or Mui-classNames removed? https://i.stack.imgur.com/J6A9V.png Similar to the image displayed? (All CSS class names would be jssXXX) Appreciate your assistance. ...

Employing specific delimiters with hogan-express while managing the {{{ yield }}} statement

I've hit a roadblock trying to solve this issue. My goal is to incorporate hogan.js (via hogan-express) into a new expressjs application while also utilizing hogan.js on the front-end with Backbone, lodash, and other tools. The layout I am using cons ...

Simple integration of JSP, JSON, and AJAX

I need help testing a simple login functionality using AJAX. Here's the code snippet: <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login Test Page</title> <script src="../js/j ...

What is the correct method for completely eliminating a mesh from the three.js scene?

I am looking for a way to fully remove meshes from a three.js scene without causing any memory leaks. I have noticed that reloading the same models multiple times can lead to browser crashes, indicating that memory is not being properly deallocated. ...

Iterating over an array of objects and executing asynchronous operations

I am currently working with NextJS and managing an array of assets (images) within my state. The task at hand is to post these images to the API. To accomplish this, I have a specific object that handles the posting process using the following syntax: let ...

What is the best way to update React State after making an asynchronous call to MongoDB?

I have been facing a common issue, but couldn't find an up-to-date solution on Stack Overflow specifically for React/Meteor. My goal is to query a mongoDB to retrieve data and then pass it into the state of my React components. Currently, I am queryin ...

How to efficiently update a nested array within the state of a React

Although the onChange function is working as expected, I am facing issues with updating the features in the state. Despite numerous attempts, I haven't been able to find examples similar to what I'm trying to achieve, so I decided to seek help. ...

What are some ways that next.js Link can prevent unnecessary server requests?

Following that, there is a need to establish connections between these pages. While an HTML tag could be used for this purpose, it would result in server requests and page refreshes, which is not the desired outcome. import Link from 'next/link&apos ...

Tips for effectively managing Angular JS dependencies and promoting modularity

As I embark on a new project from the ground up, my main focus is creating a responsive website optimized for mobile devices. In order to achieve this goal, I am seeking information about Angular: How does Angular manage its resources and dependencie ...

Iterate over a JSON object to calculate the total sum of values based on distinct nested properties

Here is a JSON object that contains cost and author information. I am working on this in Express.js and using Underscore. [ { "Cost": 250, "author": { "id": "2", "name": "Joe", "workId": "5" } }, { ...