DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Week 5 : API's and stuff....
Deepak Kumar
Deepak Kumar

Posted on • Updated on

Week 5 : API's and stuff....

It is already my week 5 in Full stack camp which focuses on helping students to grow their technical skills. Here is what I learned in week 4.

What was I doing wrong till now☹️☹️

Earlier when I was starting to learn to code as everyone alike I started with C programming Language, but left it midway and moved to C++ and funny part is even left that midway and moved on to another language....

So basically I became Jack of all and Master of none..πŸ˜…πŸ˜…
That's the biggest mistake, before starting something first make sure that will it be relevant to what you are doing now or what you are gonna do in the future and above all if you are even interested in doing it, because if you are not you are gonna leave things midway and move on.

The main focus should be go slow and steady and finish the race and not run fast and stop midway...

What did I do this week🀨🀨

This week I learnt about API stands for Application Programming Interface.. Basically it is an interface to allow two applications to talk to each other.

I learned about fetching data from an External API and displaying it in my app...

Yes yes I also built a mini project using Lorem picsum api, which generates random images every time there is a network call(using form submission, on clicks or simply reloading pages)

Alt Text

Creating the app

At first we would need a state variable for storing the image that is returned by the api and two more state variables for keeping the loading states and error states.

  const [image, setImage] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
Enter fullscreen mode Exit fullscreen mode

Now we would need to write a function to fetch the image from the picsum api and store the result in a state variable that we created:-

 const fetchImage = () => {
    setLoading(true);
    setError(null);
    fetch("https://picsum.photos/500").then(
      (result) => {
        setLoading(false);
        setImage(result.url);
      },
      (err) => {
        setLoading(false);
        setError(err);
      }
    );
  };
Enter fullscreen mode Exit fullscreen mode

This uses the native fetch method to hit the picsum api endpoint which in turn returns the url.
Before starting the request we are setting the loading state to true so as to tell the application that we are doing something now.After fetching the result we would set loading state to false and set the image url in the image state variable that we created by using setImage(result.url).

Besides this we can also use async await syntax to do the same thing:-

const fetchImage = async () = >{
  setLoading (true);

  try {
    const result = await fetch ("https://picsum.photos/500");
    setImage (result.url);
  } catch (err) {
    setError (err);
  }
  setLoading(false);
};

Enter fullscreen mode Exit fullscreen mode

Now we need to call this function only when the component initially loads, so for this we would use the useEffect() hook.

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

Enter fullscreen mode Exit fullscreen mode

Here the empty dependency array means call the function only when component loads initially.

Now we would create a component to use the following variable and show some content

  <div className="App">
      {error ? (
        <h3>Failed to fetch</h3>
      ) : loading ? (
        <Loader />
      ) : (
        <ImageDisplay image={image} />
      )}
      <br />
      <Button variant="outline-primary" className="mt-2" onClick={fetchImage}>
        Get Image
      </Button>
    </div>

Enter fullscreen mode Exit fullscreen mode

Here is the github repo and if you want to try it out Go Here..

That's it do connect with me on LinkedIn , Github ..

Keep doing and keep learningπŸ”₯πŸ”₯..

Top comments (0)

🀯

"I made 10x faster JSON.stringify() functions, even type safe"

☝️ Must read for JS devs