skip to Main Content

i want to use a dynamic array as input in dependency array of useEffect hook. But the array is going as a string and so not triggering the hook in the correct way.

const [formData,setFormData] = useState({
    name: '',
    age: '',
    place: ''
})

let receivedDynamicArray = ['formData.name','formData.age']

useEffect(()=>{
    // do something
},[...receivedDynamicArray])

Has anyone faced such an issue before?. If yes please share how you resolved this.
Thank you.

i tried using the eval and JSON.parse functions for the dynamic array to make it non-string, but that didnt work either.

2

Answers


  1. In JavaScript, the values in an array are typically passed as references. However, in your case, you are passing a string representation of the array elements, which is causing the issue. Instead of using the spread operator (…) directly on the string array, you need to evaluate the expressions inside the string array to access the corresponding values from the formData object.

    To achieve this, you can use the map() method to iterate over the receivedDynamicArray, evaluate each expression using eval(), and retrieve the actual values. Here’s an example of how you can modify your code:

    enter code here
    const [formData, setFormData] = useState({
      name: '',
      age: '',
      place: ''
    });
    
    let receivedDynamicArray = ['formData.name', 'formData.age'];
    
    const evaluatedArray = receivedDynamicArray.map(expression => eval(expression));
    
    useEffect(() => {
      // do something
    }, evaluatedArray);
    

    In the above code, the evaluatedArray variable will contain the actual values of the name and age properties from the formData object. Now, when any of these values change, the useEffect hook will be triggered accordingly.

    However, it’s important to note that using eval() can be potentially unsafe, especially if the evaluated expressions come from user input. It’s generally recommended to avoid using eval() and instead find alternative approaches to achieve your desired functionality.

    Login or Signup to reply.
  2. You can watch formData directly, here is an example.

    const [formData, setFormData] = useState({
        name: '',
        age: '',
        place: ''
    })
    const prevFormDataRef = useRef();
    let receivedDynamicArray = ['name', 'age']
    useEffect(() => {
        // Loop over receivedDynamicArray, check changes for each field
        receivedDynamicArray.forEach(field => {
            if (prevFormDataRef.current && prevFormDataRef.current[field] !== formData[field]) {
                // do something
            }
        });
        prevFormDataRef.current = formData;
    }, [formData])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search