Next.js Discord

Discord Forum

how to run function once after the app load for the first time?

Answered
Ashy Storm-Petrel posted this in #help-forum
Open in Discord
Ashy Storm-PetrelOP
so am trying to make fetch function and save the data locally but i don't want to run the function again in every change in the page i want it to run once and stay untill refresh or app open again from google or link
Answered by joulev
fetch it in the root layout
View full answer

20 Replies

@Coffee Coke try using useEffect
Ashy Storm-PetrelOP
i know and tried it but it keep running on every page change
when going from
/
to
/app

the useEffect with empty array runs
Ant
use boolean and set it to false after first render and set something like if(!isInitialRender){
return
}
callFunction();

in useEffect
Ashy Storm-PetrelOP
i just did it runs the whole useEffect again so the state reset
  useEffect(() => {


    let isFirstRender = true
    if (isFirstRender) {
      isFirstRender = false
      console.log("test")
    }
  }, [])
Ant
dont do it inside
Ashy Storm-PetrelOP
you mean like useState or?
i tried setting it outside normal variable and useState same result
Ant
try like this
const [firstRender,setFirstRender] = useState(true);

  useEffect(() => {
  if(!firstRender){
return
}

callFunction();
setFirstRedner(false
);
  }, [])
Ashy Storm-PetrelOP
same result it redo every time the page changes to another one
i just read next uses file base routing so there's no way to communicate between pages so i guess each page doesn't know if it run that function or not
what i will be doing is saving in localStorage and set timer and if the timer run out to run the function
thank you guys for the help
Ant
U can try something like this
const CommentsSheet: React.FC<CommentsLocationIdProp> = ({ locationId }) => {
  const [comments, setComments] = useState<CommentsPropsData[]>([]);
  const [loading, setLoading] = useState(true);
  const isFetchedData = useRef(false);

  const fetchComments = async () => {
    setLoading(true);
    const commentsData = await getAllComments(locationId);
    setComments(commentsData);
    setLoading(false);
  };

  const handleOpen = () => {
    if (!isFetchedData.current) {
      isFetchedData.current = true;
      fetchComments();
    }
  };
...

thats what i did for sheet component to stop refething on every open button
Ashy Storm-PetrelOP
still the same problem

the issue is not that i don't want it to refetch on click/action

i want it to run once when the app loads for the first time and never run again between pages which seem to be impossible becuase each page doesn't know if the previouse page ran or not
Answer
@joulev fetch it in the root layout
Ashy Storm-PetrelOP
that would be correct! i just tried it and the root layout fetch once and that it untill they refresh
thank you