MOFD
MOFD

Reputation: 253

Add a Spinner while waiting for promise to resolve in react

const fetchMusic= () => {
  return new Promise((resolve) =>
    setTimeout(() => {
      const music = musicList.sort(() => 0.5 - Math.random()).slice(0, 4);
      resolve({ data: music});
    }, 300)
  );
};

export default fetchMusic;


const getRandomMusic = () => {
  return fetchMusic().then((result) => result.data);
};

const Button = (props) => {
  return (
    <div>
      <Button {...props} onClick={getRandomMusic.bind(this)} />
      <SomeComponent /> 
      <p>Some text here</p>
    </div>
  );
};

I want add a spinner while waiting for the promise to resolve . fetchMusic is in some other file.I m importing it in a component .

Upvotes: 1

Views: 5526

Answers (1)

Stark Jeon
Stark Jeon

Reputation: 1145

TLDR

How about use useState and useCallback for that action

Answer

At terms of react, use State for loading action is right use case.
So, When to start function, use can setLoading(true) and after action you can setLoading(false) for make loading effect


const fetchMusic= () => {
  return new Promise((resolve) =>
    setTimeout(() => {
      const music = musicList.sort(() => 0.5 - Math.random()).slice(0, 4);
      resolve({ data: music});
    }, 300)
  );
};

export default fetchMusic;

const Button = (props) => {
  const [loaidng, setLoading] = useState(false);
  const getRandomMusic = useCallback(() => {
      setLoading(true)
      return fetchMusic().then((result) => {
        setLoading(false);
        result.data
      });
  },[]);
  return (
    <div>
      <Button {...props} onClick={getRandomMusic.bind(this)} />
      {loading && <Sipinner/>}
      <SomeComponent /> 
      <p>Some text here</p>
    </div>
  );
};

Reference

  1. Example of loading

ETC

If you have any other question. Just give me comment please.

Upvotes: 1

Related Questions