Reputation: 35
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.
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.
Upvotes: 0
Views: 1196
Reputation: 196
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.
Upvotes: 3