Michael Malura
Michael Malura

Reputation: 1181

Constant behaves different in webpack production build

Right now my development build behaves like it should. I render a list of projects and each entry in the lists has project.id as a key. All entries in the list are different as i would expect.

This is the code which works fine.

for (const project of sortedProjects) {
    if (project.id) {
        projects.push(
            <ProjectListItem
                key={project.id}
                project={project}
            />,
        );
    }
}

Now i want to cleanup a bit and create a const projectId = project.id;.

for (const project of sortedProjects) {
    const projectId = project.id;
    if (projectId) {
        projects.push(
            <ProjectListItem
                key={projectId}
                project={project}
            />,
        );
    }
}

The webpack production build is now broke because every project in the list is the same. I think somehow the projectId is the same for every entry. But my tests don't reflect that. When i log (console.log({ project, id: project.id, projectId });) the projects and ids everything is unique as it should be.

const { id } = project; would work too.

Upvotes: 5

Views: 175

Answers (1)

Shiraz
Shiraz

Reputation: 2830

Is projects initially an empty array? If so, you could do the following:

const projects = sortedProjects
    .filter((project) => project.id)
    .map(
      (project) => <ProjectListItem key={project.id} project={project} />
    );

Like others have said, I doubt the issue relates to webpack. As this is a React related issue, just make sure you haven't done something silly like setting id based on a transient value like index within a sorted array. Keys need to be unique identifiers that don't change based on state.

Upvotes: 3

Related Questions