Home > database >  Why does it say that my variable is not defined?
Why does it say that my variable is not defined?

Time:08-16

Here is my react component... I can't figure out why nyVariable says that it is not defined...

import React from "react";
import { useEffect } from "react";

const Component = () => {

  useEffect(() => {
    const myVariable = "Jim"
  }, []);

  return(<div>{myVariable}</div>) 
};

export default Component;

Thanks!

CodePudding user response:

A variable created inside a useEffect can not be accessed from outside the useEffect. I would recommend looking into how a useEffect and useState work.

Try something like this:

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

const Component = () => {
  const [state, setState] = useState("");
  useEffect(() => {
    setState("Jim");
  }, []);

  return(<div>{state}</div>) 
};

export default Component;

This will create a state variable that contains an empty string. Then upon the components first render, will set the state to "Jim".

CodePudding user response:

Your are getting undefined because of the scope rule in javascript. Try to do it this way.

import React from "react";
import { useEffect } from "react";

const Component = () => {
  const myVariable = "";

  useEffect(() => {
    myVariable = "Jim"
  }, []);

  return(<div>{myVariable}</div>) 
};

export default Component;

Because your defining your variable inside useEffect (Function) it is available only inside this function. you will not be able to access it outside. This is why I declared it outside first and then updated it value inside the useEffect hook.

  • Related