I am working on a react app that shortens a URL after a button is clicked. I am having a hard time figuring out the best logic to do so. The loading message does not show then when I click the button. The loading button appears and then disappears when the message loads.
The current behavior with the code below is the following.
- When it renders "Loading..." does not show.
- I click my "Shorten it" button and "Loading..." shows.
- The shortened url appears below the "Loading..." button.
Shorten.js
import { useEffect, useState } from "react"; const Shorten = () => { const [shortLink, setShortLink] = useState(null); const [isPending, setIsPending] = useState(false); const [input, setInput] = useState('example.org/very/long/link.html'); const url = "https://api.shrtco.de/v2/shorten?url="; const fullUrl = (url.concat(input)); console.log(fullUrl); useEffect(() => { fetch(fullUrl) .then(res => { return res.json(); }) .then(data => { setShortLink(data.result.short_link); // setIsPending(false); }) }, [fullUrl ]) // input // value={input} const loadMsg = () =>{ setIsPending(true); } return ( <main> <section className="purple-card"> <input onInput={e => setInput(e.target.value)} type="text" placeholder="Shorten a link here..." className="shorten-input"/> <button className="shorten-it" onClick={() => loadMsg()}>Shorten It!</button> </section> <section className="white-card"> {isPending && <div className="loading-text">Loading...</div>} {shortLink && <div className="shorten-text">{shortLink}</div>} <hr></hr> <button className="shorten-it" >Copy</button> </section> </main> ); } export default Shorten;
https://stackoverflow.com/questions/67013426/react-loading-msg April 09, 2021 at 08:13AM
没有评论:
发表评论