How to copy React Props array to another usestate array

SetPostData is React Props and it’s contained some array data
i need to copty SetPostData to the post
How i do this ?

export default function Post({ SetPostData }) {

    const [post , setPost] = useState([])

    useEffect(()=>{        
        setPost(SetPostData);
        likejPost()
    },[])

return (
<div>............</div>
)
}

I believe you can achieve this either by:

  • Passing SetPostData as a state value to the post in your hook or
  • Using the spread operator copy the contents of the SetPostData into your useState.
    Because right now your post is an empty array and if you would like to have the post’s state value to be whatever value coming from the SetPostData you might have to try the steps mentioned above.

Also it might help if you can provide some steps you have tried.

1 Like

SetPostData always carries an some array
Therefore i like to do first method

@teamie

    const [post,setPost] = useState(SetPostData)

I did it this way

If you try to destructure in the component you’ll encounter some bugs. Try to omit the SetPostData as a parameter and pass it directly into your hook like I suggested and the post state will be set to the values coming from the SetPostData

Yes. This would work and you can now play around with the values coming from the SetPostData.
And if you want to manipulate the state value for post you can now do that in the useEffect and I’d advice setting up an empty dependency (This can cause endless loop of re-rendering if you add irrelevant dependencies) except you know that whatever dependency you’re passing into your useEffect will definitely change.

1 Like

If SetPostData is never changed inside the Post component you shouldn’t need it as state, it can be used directly as a prop.

If you do set it inside a useEffect SetPostData should be part of the dependencies array (you should see a warning in your IDE). By the way, if SetPostData is an array I’m not sure why it has Set in the name, that just makes it sound like a function/method.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.