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

Update list display in Next.js when passing data from children

I have a Page component in Next.js that looks somewhat like this:

export default function Index({ containers }) {
  const [containerListState, setContainerListState] = useState(containers);

  const updateContainerList = (container) => {
    containers.push(container);
    setContainerListState(containers);
  };

  return (
    <>
      <FormCreateContainer updateContainerList={updateContainerList} />
      <ContainerList containers={containerListState} />
    </>
  );
}

FormCreateContainer allows for the creation of a container. When that API call resolves, I call updateContainerList and pass the newly created container to the parent. This works.

However, I also want to pass this container to ContainerList (which is a simple dynamic list using containers.map()) as part of the containers prop. While pushing to containers works as intended, Next does not live-update my list of containers; the newly created container only shows up when I reload the page.

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

I thought that including useEffect and changing updateContainerList as follows might work, but alas it did not.

  const updateContainerList = (container) => {
    containers.push(container);
  };

  useEffect(() => {
    setContainerListState(containers);
  }, [containers]);

How do I correctly pass data from a child to a parent component, therethrough passing it to a different child component and updating a dynamic list without reloading the page myself?

I really do appreciate any help as I have done extensive research that did not help me achieve my goal.

>Solution :

First and foremost, you should never mutate the value of a prop.

I think you should just use setContainerListState to update the data without mutating the prop like this:

const updateContainerList = (container) => {
    setContainerListState(containers => [...containers, container]);
};

This will re-render your component and all its children automatically.

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