skip to Main Content

I need to display users public name via reactjs as per {publicName}
OR {pubname}

but it throws error, publicName is not defined

Here is my Code:

import React, { useEffect, useState, Fragment } from "react";

const fetchAccountId = async () => {
  const publicName = "Nancy Moore";
  return publicName;
};

function App() {
  const [accounts] = useState(fetchAccountId);
  fetchAccountId();

  const [pubname, setPubname] = useState(null);
  setPubname(publicName);

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

  return (
    <div>
      <h2> Display Public Name</h2>

      <div>
        {publicName}
        OR {pubname}{" "}
      </div>
    </div>
  );
}

export default App;

2

Answers


  1. Since there is no such publicName defined in the scope and thus error.

    There are following issues in your code snippet:

    1. You have to have publicName defined in the scope to access it.
    2. You shouldn’t be setting state in the code directly in components. It will cause infinite renders.
      Better to use useEffect and set state in it. So that it will set state only if it is required.

      useEffect(() => {
        fetchAccountId().then((publicName) => setPubname(publicName));
      }, []);
    

    You can also use async-await if you prefer to use it:

      useEffect(() => {
        (async () => {
          const publicName = await fetchAccountId()
          setPubname(publicName);
        })();
      }, []);
    

    CODESANDBOX

    import React, { useEffect, useState, Fragment } from "react";
    
    const fetchAccountId = async () => {
      const publicName = "Nancy Moore";
      return publicName;
    };
    
    function App() {
      const [accounts] = useState(fetchAccountId);
    
      const [pubname, setPubname] = useState(null);
    
      useEffect(() => {
        fetchAccountId().then((publicName) => setPubname(publicName));
      }, []);
    
      return (
        <div>
          <h2> Display Public Name</h2>
    
          <div>{pubname}</div>
        </div>
      );
    }
    
    export default App;
    
    Login or Signup to reply.
  2. Just need on adjustment, add change

    fetchAccountId();
    

    with

    const publicName = fetchAccountId();
    

    and it would be better if you use it in useEffect().

    useEffect(() => {
      const publicName = fetchAccountId();
      setPubname(publicName);
    }, []);
    

    This use effect function will trigger when component is loaded.

    Note: the const publicName in fetchAccountId() is not a global variable it only exists within the fetchAccountId() function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search