Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UseEffect - Use state to create an external Link

I have a method getUrl() calling an API endpoint

  useEffect(() => {
    getUrl()
      .then(x => x.json())
      .then(x => {
        const { result } = x;
      });
  });

I can see in the Console the call in my page as you can see in the screenshot this is my data

{
   "result":"https://www.google.it",
   "error":null,
   "errorCode":null,
   "isSuccessful":true,
   "operationStatusCode":"OK"
}

How can I display the following result link example https://www.gooole.it in an external link in my view?

Do I have to use states?

I need an example of how to code to do this here

<a target="_blank" href={result}>Google Link</a>

enter image description here

like image 499
Koala7 Avatar asked Feb 24 '20 12:02

Koala7


People also ask

Can useEffect set state?

Can I set state inside a useEffect hook? In principle, you can set state freely where you need it - including inside useEffect and even during rendering. Just make sure to avoid infinite loops by settting Hook deps properly and/or state conditionally.

Can I set state inside a useEffect Hook?

We can set state inside the useEffect hook by merging the values of the existing state with the new values and returning that as the state in the state updater function.

How do I use useEffect as componentWillUnmount?

To clean up after a component unmounts, we have a simple way to perform the equivalent of the componentWillUnmount using the useEffect Hook. The only thing that we need to do is to return a function inside the callback function of the useEffect Hook like this: useEffect(() => { window.

Can I use useRef instead of useState?

If you want to update data and cause a UI update, useState is your Hook. If you need some kind of data container throughout the component's lifecycle without causing render cycles on mutating your variable, then useRef is your solution.

Can I set state inside a useeffect hook?

▶ 1. Can I set state inside a useEffect hook? In principle, you can set state freely where you need it - including inside useEffect and even during rendering. Just make sure to avoid infinite loops by settting Hook deps properly and/or state conditionally. ▶ 2. Lets say I have some state that is dependent on some other state.

What is the difference between useeffect() and usestate()?

As a rule of thumb, useEffect () executes right after useState (), so once the useState () has rendered the first object of the original array, the useEffect () is invoked and in turn it invokes setInterval function. The setInterval function as it is defined in the official MDN Web Docs:

Is it possible to use setState inside useeffect?

Generally speaking, using setState inside useEffect will create an infinite loop that most likely you don't want to cause. There are a couple of exceptions to that rule which I will get into later.

Can I use multiple useeffect statements in a component?

On top of that, useEffect blocks are candidates to extract into reusable and even more semantic custom Hooks. Don’t be afraid to use multiple useEffect statements in your component. While useEffect is designed to handle only one concern, you’ll sometimes need more than one effect.


2 Answers

You have to use a state in your component :

const [url,setUrl] = useState('');

and render it :

<a target="_blank" href={url}>Google Link</a>

and in the use effect :

useEffect(() => {
   getUrl()
     .then(x => x.json())
     .then(x => {
        const { result } = x;
        // use set url hook 
        setUrl(result);
      });
  });
like image 175
LHIOUI Avatar answered Oct 10 '22 09:10

LHIOUI


Do I have to use states?

Yes! you should use state object to maintain the fresh results as setState can be async and when you update the state a rerender takes place and UI gets updated. Check this:

Put this to initialize the state:

const [result, setResult] = useState({});

where result is a property and setResult will be the updater method.

Now you have to use it in the component's template such as :

{ result && <a target="_blank" href={result}>Google Link</a> }
{/* if result (its a promise) is not available when render happens then it might err. */}

Now in your useEffect:

useEffect(() => {
    getUrl()
      .then(x => x.json())
      .then(x => {
        const { result } = x;
        setResult(result); // <-----------set it here
      });
  },[result]); //<---pass it here it rerenders when state.result changes after first render.
like image 21
Jai Avatar answered Oct 10 '22 07:10

Jai