Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

207
Vistas
store function names in an array and call them one by one using array.forEach()

I am building a react-native has which has almost 15 states to store some data. Now I want is store all these values (and fetch all of them) in/from internal storage, I'm using react-native-mmkv.

//functions from context api
const {setUsername, setToken, setProgress} = useAppContext();

const getsettingsconfig = () => {
    const keys = storage.getAllKeys();
    console.log(keys);  // ['setProgress', 'setUsername', 'setToken']
    keys.forEach(key => {
      const data = storage.getString(key);
      // I want to set all the values dynamically here
      key(parsedData); // setProgress(data), setUsername(data) etc. like this
    });
  };

useAppContext.js

import { createContext, useContext } from "react";

export const GlobalContext = createContext({});

export default function useAppContext() {
  return useContext(GlobalContext);
}

However, I keep getting

 [TypeError: 'setProgress' is not a function]

What am I doing wrong here?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This is one possible way to execute a function whose name is present in an array. The trick here is mapping the name of the function with the function itself (by using the object myObj). Then, one simply accesses the object with the key, and executes the function (which is the corresponding value in myObj object).

// declaring, defining 4 functions here
// this may even be from useState - same will work
const setField1 = d => console.log('setField1, data: ', d);
const setField2 = d => console.log('setField2, data: ', d);
const setField3 = d => console.log('setField3, data: ', d);
const setField4 = d => console.log('setField4, data: ', d);

// declaring an array of functions
// this can be populated from local-storage - and it will work
const fnArr = [setField1, setField2, setField3, setField4];

// for-each loop to execute each function in the array
fnArr.forEach((fn, idx) => fn(idx));

// using a string array - which will not execute the functions
console.log("\n\n can't execute strings as functions\n\n");
const strArr = ['setField1', 'setField2', 'setField3', 'setField4'];
strArr.forEach(st => console.log(`'${st}' is a string & not a function... one can't execute it`));

// executing the same functions by using the string keys
console.log('\n\n executing functions by using string-names as keys\n\n');
const myObj = Object.fromEntries(strArr.map((k, idx) => ([ k, fnArr[idx]])));
strArr.forEach((k, idx) => myObj?.[k](idx));
.as-console-wrapper { max-height: 100% !important; top: 0 }

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda