Home > OS >  How to load data from a DB only once in react?
How to load data from a DB only once in react?

Time:03-24

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?

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

You need to only add the [] inthe end of the useeffect hook in recta whie compoennt load than automaticlly load the data and not run this use effect in many times

CodePudding user response:

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))
}, [])
  • Related