Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React – Calling a function of all class instances in an array state stored in a ContextProvider

I have a provider that stores and adds ‘People’ to a state. This state is then exposed to the rest of the application. Everything works as expected, however when I get the instances of the classes I am unable to call their function. It returns undefined whenever I try to call it. The code itself does not error, but also doesn’t work. Do you have any insight as what might be going wrong?

Person class:

export class Person {
    private name: string;
    constructor() {
        this.name = uniqueNamesGenerator(config);
    }

    getName() {
        return this.name;
    }

}

The provider

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export const PeopleProvider = ({ children }: PropsWithChildren) => {
    const [ people, setPeople ] = useState<IPerson[]>([]);

    const addPerson = () => {
        setPeople([ ...people, new Person() ]);
    };

    const getInstances = (): IPerson[] => {
        return people;
    };

    return (
        <PeopleContext.Provider value={{ addPerson, getInstances }}>
            {children}
        </PeopleContext.Provider>
    );
};

The component

export const Home = () => {
    const { addPerson, getInstances } = usePeople();

    const add = () => {
        addPerson();
    };

    const getNames = () => {
        const people = getInstances();
        console.log(people);
        console.log(people.forEach(p => p.getName())); // <==== undefined
    };

    return (
        <Grid container>
            <Grid item xs={2}>
                <Typography>Settings</Typography>

                <Button onClick={add}>add</Button>

                <Button onClick={getNames}>get names</Button>
            </Grid>

            <Grid item xs={10}>
                <Typography>Side</Typography>
            </Grid>
        </Grid>
    );
};

When looking in the console, all objects do have a name and a getName function in their prototype. Any idea what might be causing the undefined here?

>Solution :

As the docs mentioned https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Array.prototype.forEach returns undefined

Try using map method

console.log(people.map(p => p.getName()))

or with forEach

people.forEach(p => console.log(p.getName()))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading