Skip to content
Sandny Blog
  • Home
  • Java
  • JavaScript
  • AWS
  • Embedded
  • About
How to fetch data with useEffect JavaScript

How to fetch data with useEffect

  • July 2, 2021July 2, 2021
  • by Coder Kai

React hooks have been very promising solution for most of the coding issues that React framework had in old days. But for novice developers, it could be hard to understand. Especially if you are moving from old react to new. One of the main problem is how to fetch data with useEffect in a proper way.

1. Why fetch data with useEffect?

Often developers face scenarios where they need to fetch data or resolve a Promise when updating a state or prop. The savior is useEffect. To first which we should understand what is useEffect.

Above is the state machine that depicts the component life cycle.

useEffect is a different than thinking this in life cycle modal. In useEffect, an Effect is a lifecycle event.
The useEffect will be called for every lifecycle event

useEffect(() => {
  console.log('Called for every lifecycle event');
});

Above code block is an example for a use Effect listening to every event. But we really don’t have a useful purpose of having a effect listener like above. Rather than that if we can specifically select the effects that we need to call the function that would be more useful.

useEffect(() => {
  console.log('Called once for initial render');
  return () => console.log('Called once when the component is unmounting');
}, []);

useEffect(() => {
  console.log('Called every time when the state or prop is updated');
}, [stateVariable, propVariable]);

With above we can see that we cannot call an async function callback in the useEffect. Synchronous function to execute a task would make the listening to effects blocking the lifecycle flow.

2. Fetch data from useEffect

Rather than that we can execute a function that makes the async function to be executed separately, thus making the callback function not blocking the execution for an effect.

const fetchUser = userId => fetch(`https://api.example.com/user/${userId}`);

// wrong implementation
const [selectedUserId, setSelectedUserId] = useState(null);
const [userData, setUserData] = useState(null);

useEffect(async () => { // cannot use async
  const userData = await fetchUser(selectedUserId);
}, [selectedUserId]);

// correct implementation
useEffect(async () => {
  const fetchUserData = async () => {
   const user = await fetchUser(selectedUserId);
   setUserData(user);
  }
}, [selectedUserId]);

// another way if you want to memoize or useCallback to initialize only once
const fetchUserData = async (selectedUserId) => {
  const user = await fetchUser(selectedUserId);
  setUserData(user);
};
useEffect(async () => {
  fetchUserData(selectedUserId); // passing parameter incase you want useCallback
}, [selectedUserId]);

Note that both of the above examples are correct but the latter one has different benefits if you don’t want to initilize the function everytime that the effect is called.

2. Handling loading and error when fetching data

Common example is if how to show an error or how show a loading spinner when fetching data from a component.

const UserComponent = ({users}) => {
    const [selectedUserId, setSelectedUserId] = useState(null);
    const [userData, setUserData] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    useEffect(async () => {
      const fetchUserData = async () => {
        try {
          setLoading(true);
          setUserData(null); // to remove previous error
          const user = await fetchUser(selectedUserId);
          setUserData(user);
        } catch(errorMessage) {
          setError(errorMessage);
          setUserData(null); // in case we need to reset state
        }
        setLoading(false);
      }
    }, [selectedUserId]);

    return (
      <div>
        {
          users.map((user) => <div key={user.userId}>{user.name}</div>)
        }
        { error && <div>Error occurred while fetching data: {error}</div> }
        { loading && <div>Loading user data...</div> }
        {
          userData && (
            <>
              <h3>User Preference and Address</h3> 
              <div>{userData.address}</div>
              <div>{userData.preference}</div>
            </>
          )
        }
      </div>
    );
}

Yep, this is a way that we can do it. But its not a good coding structure. Lets try to improve this.

3. Custom hooks

We can do it by using a custom hook. To create a custom hook we need to always state the function with use name.

const useUser = (initialUser) => {
  const [userData, setUserData] = useState(initialUser);
  const [selectedUserId, setSelectedUserId] = useState(initialUser.userId);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(async () => {
    const fetchUserData = async () => {
      try {
        setLoading(true);
        setUserData(null); // to remove previous data
        const user = await fetchUser(selectedUserId);
        setUserData(user);
      } catch(errorMessage) {
        setError(errorMessage);
        setUserData(null); // in case we need to reset state
      }
      setLoading(false);
    }
	}, [selectedUserId]);
  
  return [{loading, error, userData}, setSelectedUserId];
}

const UserComponent = ({users}) => {
    const [{loading, error, userData}, setSelectedUserId] = useUser(users[0]);

    return (
      <div>
        {
          users.map((user) => <div key={user.userId}>{user.name}</div>)
        }
        { error && <div>Error occurred while fetching data: {error}</div> }
        { loading && <div>Loading user data...</div> }
        {
          userData && (
            <>
              <h3>User Preference and Address</h3> 
              <div>{userData.address}</div>
              <div>{userData.preference}</div>
            </>
          )
        }
      </div>
    );
}

Here the custom hook takes the effect updates seperately and that allows the component code to be minimum and use the atomic effect to render the component

Is that it?

Nope; there are many other ways to utilze the effects and render the components very efficiently.

  1. Using useReducer
  2. Using Suspense and lazy loading
  3. Using redux, recoil or any other state management framework

Also one thing to note down is there are fetch libraries that really helpful in this.

  1. Apollo client(GraphQL) has useQuery, useMutation hooks that gives the loading, error, data etc as return variables.
  2. Libraries like useFetch which also give custom hooks for http, https requests.
    Ex: const { loading, error, data = [] } = useFetch('https://example.com/todos', options, [])

Let me know what else you have discovered to make this more easy to use and scale with the code.

How to add styles to stripe elements without using CardElement
03. Javascript Guide – Strings
Coder Kai
A humble developer
custom hooks fetch react.js useEffect useFetch

Related articles

Multiple refs for an array of React Elements
Using multiple refs for an…
Immutable and Mutable Values in Javascript
07. Immutable and Mutable Values…
wrapper objects in javascript
06. Wrapper objects in Javascript
globals undefined and null values in javascript
05 Global, null and undefined…
Javascript Booleans and Equality
04. Javascript Guide Booleans and…
How to add Chakra UI Animations
Chakra UI Animations
SSL Websocket using Nginx Proxy
SSL Websocket proxy with Nginx…
Change python version correctly
Python is not setting correct…
optimize React.js load time
How to optimize React.js app…
Multiple refs for an array of React Elements
How to use IntersectionObserver to…
Multiple refs for an array of React Elements
How to dismiss dropdowns when…
Javascript guide Strings
03. Javascript Guide – Strings
add styles to stripe elements
How to add styles to…
Typescript
How to use Typescript with…
how to optimize react-native map view
How to optimize react-native map…
debounce with react hooks
Avoid multiple clicks using debounce…
Numbers inJavascript
02. Javascript Guide – Numbers
Introduction to Javascript
01. Javascript Guide – Introduction…
Nginx Load Balancer with docker…
Create React App Using npx
23 COMMENTS
  • Boolep
    July 11, 2022 at 2:58 pm
    Reply

    paroxetine 7.5 mg coupon

  • Mialep
    August 10, 2022 at 10:12 am
    Reply

    synthroid nz

  • Darrylecose
    August 17, 2022 at 11:23 am
    Reply

    albendazole drug cost zoloft 15 mg vermox uk clindamycin price

  • JamesNeith
    August 18, 2022 at 10:54 am
    Reply

    tetracycline 100 mg tetracycline 1000 mg cleocin 150 price how much is a zoloft prescription buy prednisolone uk lexapro 20mg buy singulair uk prednisolone 3 mg

  • lasserix
    October 1, 2022 at 10:39 am
    Reply

    concise and clean, was looking for just this kind of example thanks

  • MiclAngen
    October 13, 2022 at 11:03 am
    Reply

    [url=http://sildenafil.lol/]buy viagra soft tabs[/url]

  • Eraldkai
    November 28, 2022 at 1:31 am
    Reply

    Finally, what I’ve been waiting for has finally come after a long day has finally arrived😍😍, I hope the next chapter will come sooner

  • Ricinerm
    December 20, 2022 at 10:18 am
    Reply

    [url=https://adiflucan.online/]medication diflucan price[/url] [url=https://happyfamilypharm.online/]legitimate canadian mail order pharmacy[/url] [url=https://baclofen.click/]baclofen price in india[/url] [url=https://happyfamilyrx.quest/]canadian pharmacy 1 internet online drugstore[/url] [url=https://abilify.life/]where to get cheap abilify[/url] [url=https://canadianpharmaceuticalstores.online/]happy family store uk[/url] [url=https://buynoroxin.monster/]noroxin drug[/url]

  • embompume
    February 3, 2023 at 1:47 am
    Reply

    The pellet was subjected to repeated centrifugations at 25, 000 and 10, 000 rpm, each for 15 min ovulation on clomid calculator Raven, New York

  • Darkquaro
    February 8, 2023 at 7:03 am
    Reply

    I am not on it, thank goodness where to buy cialis cheap lopressor obat omeprazole harga Employees must update their enrollment status by Aug

  • netent demo
    April 12, 2023 at 8:58 am
    Reply

    Thank you for another magnificent article. Where else could anyone get that kind of info in such an ideal way of writing? I have a presentation next week, and I’m on the look for such information.

  • paus4d
    April 20, 2023 at 2:12 am
    Reply

    This article is very informative and taught me new things about the topic.

  • isototo
    May 10, 2023 at 4:05 pm
    Reply

    Your article is well-researched and well-written. I appreciate the effort you put into providing valuable information to your readers.

  • isototo slot
    June 2, 2023 at 1:43 pm
    Reply

    This is a fantastic article that provides practical tips and advice. I appreciate the way you presented the information in a way that is easy to follow and relevant to readers.

  • paus4d
    June 2, 2023 at 2:10 pm
    Reply

    I really like the way you structured this article. Your writing is clear and concise, and the information is presented in a logical and easy-to-follow manner.

  • actismate
    June 12, 2023 at 10:00 am
    Reply

    Although hospitals and physician offices may face increases in price, their demand for the prescription medications used to treat their patients is also not very responsive to the price paid to manufacturers for the drug 5 can’t get erect with viagra But there is more to using anabolic steroids than just appearing to be the person you have always imagined yourself to be

  • paus4d
    June 12, 2023 at 5:35 pm
    Reply

    I’m always impressed by the level of research and detail you put into your articles. It shows how committed you are to providing high-quality content.

  • isototo
    June 12, 2023 at 6:56 pm
    Reply

    Your talent for communicating complex ideas in a simple and approachable way is impressive, making your writing engaging and easy to read.

  • prediksi hk
    June 28, 2023 at 10:57 pm
    Reply

    Your article has given me a lot to think about and has sparked some great discussions with my friends and family. Thank you for providing such thought-provoking content.

  • Arteriupt
    July 24, 2023 at 8:43 pm
    Reply

    Bonferoni, M buy cialis online us Greenberg PL, The Myelodysplastic Syndromes, in Hoffman R, et al

  • Paus4d Login
    July 25, 2023 at 2:29 pm
    Reply

    Your ability to break down complex ideas into simple, easy-to-understand language makes the information more accessible.

  • isototo
    August 4, 2023 at 9:42 pm
    Reply

    Your article was informative and easy to read. Thank you for presenting the information in a way that’s easy to understand.

  • 🎁 Get free iPhone 15: http://lhci.clinic/upload/go.php 🎁 hs=84cce42c03c3755da4f2aa56ad20c93f*
    December 10, 2023 at 5:59 am
    Reply

    w2tkq0

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • android 3
  • Apollo Client 1
  • AWS 8
    • AppSync 5
    • EC2 1
    • EKS 1
    • Route53 1
    • S3 1
  • AWS Amplify 1
  • Chakra UI 1
  • Docker 1
  • Embedded 1
  • EmberJS 1
  • FCM 1
  • Godaddy 1
  • GraphQL 3
  • ios 1
  • Jasper 1
  • Java 10
    • Java 11 1
    • Java 14 1
  • JavaEE 2
  • JavaScript 39
    • Express.js 4
    • Javascript Guide 7
    • Node.js 3
    • react-native 4
    • React.js 17
    • Typescript 1
  • Kubernetes 1
  • machine learning 1
  • Maven 2
  • OCaml 3
  • PostgreSQL 1
  • Python 2
  • react-native 4
  • ReactJS 3
  • sass 1
  • Server 6
  • spark 1
  • Terraform 2
  • Ubuntu 4
  • Uncategorized 1
  • webpack 2

Recent Comments

  • Massive Health on Chakra UI Animations
  • Lexitoto on How to use AWS Ingress ALB with EKS
  • 🎁 Get free iPhone 15: http://lhci.clinic/upload/go.php 🎁 hs=84cce42c03c3755da4f2aa56ad20c93f* on How to fetch data with useEffect

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Archives

  • October 2022 3
  • September 2022 7
  • May 2022 1
  • December 2021 1
  • August 2021 1
  • July 2021 6
  • June 2021 3
  • February 2021 1
  • July 2020 1
  • December 2019 5
  • November 2019 6
  • October 2019 3
  • August 2019 1
  • March 2019 1
  • February 2019 1
  • January 2019 2
  • December 2018 1
  • September 2018 2
  • August 2018 1
  • June 2018 1
  • February 2018 1
  • November 2017 2
  • October 2017 5
  • September 2017 1
  • June 2017 1
  • May 2017 10
Sandny Blog space
Theme by Colorlib Powered by WordPress