Home > Software engineering >  How to create a method to be called each time in React
How to create a method to be called each time in React

Time:08-17

I am quite new to React and want to create a const method like this:

async function RunTest() {
  <some logic here> 
  return <a value here> } export const myMethod = RunTest();

and then import it in a service and use it like:

export async function getValue() {
  const myClient = await myMethod;
  <some logic here>
  return res.data; }

The thing is, the method RunTest will be called once when initializing. However, what I want is the content to be run each time when method GetValue in the service is called.

Any suggestions to change the myMethod without changing anything in the service as I have many of those services and don't want to change all of them. If no other way, then I have to go to every single service and change it there.

CodePudding user response:

It's running because you are putting parenthesis at the end of RunTest when exporting it. If you want to rename the export, use the as keyword in the import.

RunTest file

export async function RunTest() {
  <some logic here> 
  return <a value here> 
}

getValue file:

import {RunTest as MyMethod} from "file-path"
export async function getValue() {
  const myClient = await myMethod();
  <some logic here>
  return res.data; }
  • Related