skip to Main Content

I’m trying to figure out a way which I can load data from the database only once to a certain component.

useEffect(() => {
   axios.get("http://localhost:5000/members")
        .then(res => {
          setMembers(res.data)
        })
        catch(error => console.error(error.message))
})

Every time this component is loaded a request is made to the server for the "members". I need a way to make a request only one time, and which is when the component is being loaded for the very 1st time. Is there a way I can go about achieving this?

4

Answers


  1. You are doing one mistake here with useEffect as second argument not passed.

    useEffect(() => {
       axios.get("http://localhost:5000/members")
            .then(res => {
              setMembers(res.data)
            })
            catch(error => console.error(error.message))
    }, [])
    
    Login or Signup to reply.
  2. Make the request outside your component’s function. Promises only resolve once but the resolved value can be retrieved any number of times.

    import axios from "axios";
    import { useEffect, useState } from "react";
    
    // Make the request here and keep a reference to the returned promise
    const promise = axios.get("http://localhost:5000/members")
      .then(({ data }) => data);
    
    const MyComponent = (props) => {
      const [ members, setMembers ] = useState([]);
    
      useEffect(() => {
        // set your state from the resolved promise
        promise.then(setMembers)
          .catch(err => console.error(err.toJSON()));
      }, []); // empty dependencies array means this only runs on mount
    
      return ( /* whatever */ );
    };
    

    Edit unruffled-elbakyan-p7q50n

    You can see in the demo that the same component is loaded 3 times but the request is only made once.

    Login or Signup to reply.
  3. You can use Context to persist data throughout application or
    you can use redux for storing data in centralized app state.

    Login or Signup to reply.
  4. You only need to add [] at the end of the useEffect hook in React. When a component loads data, it will not run this useEffect multiple times.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search