Home > OS >  Shared state between Parent and Child component
Shared state between Parent and Child component

Time:03-21

I am building a front in Next.js. I have nested a component inside another, and I would like the two components to share an array of Ids.

The main component is a page that allows the user to create a collection that includes some of his posts. It sends a post request with a collection_name and the array_of_ids.

The other component that is nested within the page displays all the posts of the user. I created another component because I need it in some other pages.

I want the user to be able to select the posts that are being display in the nested component by clicking on them, and get their ids in the main component.

The main component :

const CreateCollection() => {

    const [collectionIds, setCollectionIds] = useState([]);

    /* rest of the state, post request*/ 

    return( 
        ...
        <Myposts collectionIds={collectionIds}, setCollectionIds={setCollectionIds}/>
        ...
        )}

The nested component:

export default function Myposts ({setCollectionIds, collectionIds}){

    const addId = (newId) =>{
        setCollectionIds(collectionIds.push(newId))  
    }

    /* rest of the state, get request*/ 

    return( 
        ...
        <div>
            {Posts.map((post) => (
                        <div key={post.id}
                            value={post.id}
                            onClick={addId(post.id)}
                        >
                            {post}</div>))}
        </div>
        ...
        )}

Whenever I add an Id from my nested component I get an error saying that "Posts.map... is not a function", and I don't get the array back in my main component.

I am still learning Next so I am a bit confused as how I should process now !

Thanks !

CodePudding user response:

setCollectionIds(collectionIds.push(newId))  

Array.push is not returning the array but the length of the array

const array = [1]
console.log(array.push(2)) // prints 2 because array.length is 2

You are effectively setting state to a number, not array, you can do:

setCollectionIds([...collectionIds, newId])  

or

setCollectionIds(collectionIds.concat([newId]))  
  • Related