skip to Main Content

im about to program a fortigate firewall configurator helper for a project for my shool.
i am stuck in a problem, i cant contribute from an external file to an useeffect hook in another file.

for better comprehension:
filepath: forticonfigurator/src/pages/Fortigate.js

Here i have the useEffect:

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get(`http://localhost:3000/configFiles/${selectedConfig}`);
        const regexHostname = new RegExp('{hostname}', 'g');
        const regexIdleTime = new RegExp('{idletimeout}', 'g');
        const replacedText = response.data
          .replace(regexHostname, hostname)
          .replace(regexIdleTime, idleTime)
          .replace('{policy}', policy ? Policy() : '')
          .replace('{services}', services ? Services() : '')
          .replace('{vpnuser}', vpnUser ? VPNUser() : '')
          .replace('{sipalg}', sipAlg ? SipAlg() : '');
          
          setContent(replacedText)
      } catch (error) {
        console.log(error);
      }
    };
    fetchData();
  }, [selectedConfig, hostname, policy, services, vpnUser, sipAlg, idleTime]);

the file i want contribute some data from:
filepath: forticonfigurator/src/components/ports/Ports40F.js

//some imports
import IntA from "../standardconfigs/portconfig/IntA";

export default function Ports40F() {

  const [selectedPort, setSelectedPort] = useState(null);
  const [isActive, setIsActive] = useState(null)
  const [enableDhcp, setEnableDhcp] = useState("disable")
  console.log(enableDhcp)


  //user input variables array
  const [portConfigs, setPortConfigs] = useState([
    { portNumber: 1, activate:'', portAlias_1:'', ipaddress_1:'', intNetmask_1: '', https_1:"", ping_1:"", addressRangeFrom_1:'',addressRangeTo_1:'', dhcpNetmask_1:'', dnsServer1_1:'', dnsServer2_1:''},
    { portNumber: 2, activate:'', portAlias:'', ipaddress:'', Netmask: '', https:"", ping:"", addressRangeFrom:'',addressRangeTo:'', netmask:'', dnsServer1:'', dnsServer2:''},
    { portNumber: 3, activate:'', portAlias:'', ipaddress:'', Netmask: '', https:"", ping:"", addressRangeFrom:'',addressRangeTo:'', netmask:'', dnsServer1:'', dnsServer2:''},
    { portNumber: "A", activate:'', portAlias:'', ipaddress:'', Netmask: '', https:"", ping:"", addressRangeFrom:'',addressRangeTo:'', netmask:'', dnsServer1:'', dnsServer2:''},
    { portNumber: "WAN", activate:'', portAlias:'', ipaddress:'', Netmask: '', https:"", ping:"", addressRangeFrom:'',addressRangeTo:'', netmask:'', dnsServer1:'', dnsServer2:''},
  ]);
  
  const handlePortClick = (portNumber) => {
    if (portNumber === selectedPort) {
      setSelectedPort(null);
      setIsActive(false);
    } else {
      setSelectedPort(portNumber);
      setIsActive(true);
    }
  }

  const handleConfigChange = (e, configKey) => {
    const updatedPortConfigs = [...portConfigs];
    const index = updatedPortConfigs.findIndex(config => config.portNumber === selectedPort);
    updatedPortConfigs[index][configKey] = e.target.value;

    if (configKey === 'activate') {
      updatedPortConfigs[index][configKey] = e.target.checked;
    }
    setPortConfigs(updatedPortConfigs);
  }

for more details here is my github repo:
https://github.com/dynamicsma/forticonfigurator

thanks in advance for any helpful hint

i already tried with export of the variables, also tried to put everything into one file but i did not manage it to work 🙁

kr

Cristian

2

Answers


  1. you can move your useEffect in another file and export it in a function.
    Util/UseEffect.js

        import React, { useEffect } from "react";
        import axios from "axios";
    
    const Effect = (selectedConfig, hostname, policy, services, vpnUser, sipAlg, idleTime, Policy, Services, VPNUser, SipAlg, setContent) =>  useEffect(() => {
        const fetchData = async () => {
          try {
            const response = await axios.get(`http://localhost:3000/configFiles/${selectedConfig}`);
            const regexHostname = new RegExp('{hostname}', 'g');
            const regexIdleTime = new RegExp('{idletimeout}', 'g');
            const replacedText = response.data
              .replace(regexHostname, hostname)
              .replace(regexIdleTime, idleTime)
              .replace('{policy}', policy ? Policy() : '')
              .replace('{services}', services ? Services() : '')
              .replace('{vpnuser}', vpnUser ? VPNUser() : '')
              .replace('{sipalg}', sipAlg ? SipAlg() : '');
              
              setContent(replacedText)
          } catch (error) {
            console.log(error);
          }
        };
        fetchData();
      }, [selectedConfig, hostname, policy, services, vpnUser, sipAlg, idleTime]);
    
    export default Effect
    

    And consume it in other files by importing it

    import UseEffect from "../Util/UseEffect";
        
        
     UseEffect(selectedConfig, hostname, policy, services, vpnUser, sipAlg, idleTime, Policy, Services, VPNUser, SipAlg, setContent )
    

    Hope this helps

    Login or Signup to reply.
  2. You can extract hooks out of components as long as the function begins with use:

    function useConfigFile(selectedConfig, hostname, policy, services, vpnUser, sipAlg, idleTime) {
      const [content, setContent] = useState('');
    
      useEffect(() => {
        const fetchData = async () => {
          try {
            const response = await axios.get(`http://localhost:3000/configFiles/${selectedConfig}`);
            const regexHostname = new RegExp('{hostname}', 'g');
            const regexIdleTime = new RegExp('{idletimeout}', 'g');
            const replacedText = response.data
              .replace(regexHostname, hostname)
              .replace(regexIdleTime, idleTime)
              .replace('{policy}', policy ? Policy() : '')
              .replace('{services}', services ? Services() : '')
              .replace('{vpnuser}', vpnUser ? VPNUser() : '')
              .replace('{sipalg}', sipAlg ? SipAlg() : '');
              
              setContent(replacedText)
          } catch (error) {
            console.log(error);
          }
        };
        fetchData();
      }, [selectedConfig, hostname, policy, services, vpnUser, sipAlg, idleTime]);
    
      return content
    }
    

    And then call it in any component you want:

    function App() {
      const content = useConfigFile(/* params */);
      return <div>{content}</div>
    }
    

    I also recommend you return a loading and error state from the hook.

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